String as Read-only Arrays in JavaScript

During a tech gathering, we were discussing how String acts as a read-only array in JavaScript in the latest browsers. Many of the developers did not know about this, so I thought to write a short post on the same. For eg: let us say you have a string as shown below:

var str = “Sample”;


Now you can access individual characters in a String, just like an array

alert(str[2]); // returns ‘m’


and even apply some array functions on it.

alert(Array.prototype.join.call(str, ",") // returns S,a,m,p,l,e,


Note: While applying array functions on the String, remember that the string is behaving like read-only array. So functions that manipulate the string won’t work!

Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

No comments: