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(, ",") // 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, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

No comments: