string [ ] operator behaves badly. JavaScript

Is this uncharted territory or I am too tired right now for deep googling?
(First published Aug 7 2011)

“[]” operator on a string literal. I could not find any mention of it in ECMA spec. I think it is a “good thing”, why not. But is it standard? Or just an “De-facto” standard?

Above does not throw an error in Chrome. Does this mean it is OK to do it, but it has no effect on string. Or does this mean Chrome team has to fix this, and throw an error?

Above behaves OK, and shows the result of the assignment. But assignment has not been made. This is because there is nothing to assign to , as string literal my friends is not a variable. But even it we are dealing with variable containing a string, as we see from previous example string variable remains unchanged, after Chrome V8 quietly goes over assignment to the result of using the [ ] operator.

Most likely adding [ ] operator to string literal, provokes V8 javascript interpreter (and most of the others like IE9 ‘Chakra‘) to create a temporary array object, made from slicing the original string ‘host’ into an array?

If this is true, is this bug or feature, in V8 Chrome and/or elsewhere? It seems it was decided (by ECMA comitee and/or V8 team) as logical, that one can do things to string literals, without exceptions being thrown, but no changes will be made to the string literal (because it is a literal not a variable) .

I am not sure what is logical for You, but this or following not throwing an exception, does not strike me as logical:

Am I missing something in here?

Update 2013 Apr

Two years later and we have the same puzzle. In both IE10 and the latest Chrome, we still can use [] aka “indexing operator” to get to characters in strings. But, assignment using the same operator silently fails.

Silent failure is a bad thing. We can not have this left in or promoted to ES6. This issue can be and should be immediately rectified by IE and WebKit team (and yes the Blink team too).

NOTE: same issue applies to both string literals and String objects.

7 thoughts on “string [ ] operator behaves badly. JavaScript”

Comments are closed.