string [ ] operator behaves badly. JavaScript

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

string indexing
dbj = {
    "string_indexing": "ABC" [0] === "A"
/* in V8 (Chrome) yields true */

“[]” 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?

var s = "ABC";
// this shows "ABC" on Chrome

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?

alert("ABC"[2] = "!");
// shows "!"

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?

var s = "ABC"[2] = "!";
// this is what is happening behind a scene
temporary = "ABC";
// do whatever You can, to the string literal"ABC")[2] = "!";
// the result of string literal change is lost
var s = temporary ;

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:

// Chrome does not throw an exception here

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.

c = "ABC"[1] ; /* leaves c with value 'B' */
s = "ABC"[1] = "+" ; /* SILENT FAILURE: leaves s with value "ABC" */

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).

"X" = "Z" ; /* throws: "ReferenceError: Invalid left-hand side in assignment"  */
 "ABC"[1] = "+" ; /* also must throw: "ReferenceError: Invalid left-hand side in assignment"  */

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

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

Comments are closed.