Search code examples
javascriptwebkit

Characters of strings accessed through [] are strings?


I ran into an unexpected behavior in both Chrome and the Node.js runtime today.

var x = 'I am a string';
console.log(x[0]); //String 'I'
console.log(x[0][0]); //String 'I'
console.log(x[0][0][0]); //String 'I'

I realize that accessing string indexes through brackets is not preferred and not universally supported, so my interest here is purely one of curiosity. What this implies to me is that strings are being built out of strings - ie, the character 'I' is itself a string with the character 'I' at index 0, which is itself a string... it's turtles all the way down.

Or this seems to imply to me that webkit just builds a new string object to return back to me every time I use the [] notation on an existing string. Both of those conclusions feel really weird to me.

Are either of them correct? What's going on under the hood when I call x[0]?

Edit: Related to below answer: Are strings object?


Solution

  • There is no "character" data type in JavaScript. All that a portion of a string can be is a string.

    Note that a string is not an object. A string is a primitive value.

    Accessing portions of strings with the [] involves first an implicit wrapping of the string value in a String instance (resulting in an object instance). The [] operator is applied to that object, you get the result (a string), and then the wrapper is thrown away. (Since the wrapper object is ephemeral the runtime is allowed to sneak around actually implementing the semantics in exactly that way.)