I've always thought that if you want to access the nth character in a string called str
, then you have to do something like str.charAt(n)
. Today I was making a little dummy test page and by mistake, I accessed it with str[n]
and to my surprise, it returned me the nth character of the string. I threw up this little purpose built page to exhibit this unexpected (to me) behaviour:
<!doctype html>
<html>
<body>
<script>
var str = "ABCDEFGH";
if (str[4] === str.charAt(4)) alert("strings can be indexed directly as if they're arrays");
var str2 = new String("ABCDEFGH");
if (str2[4] === str2.charAt(4)) alert("even if they're declared as object type String");
</script>
</body>
</html>
It wasn't always like this, was it?