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!

No comments:

Post a Comment