3

I have experienced a problem on a page under IE11, which crashes a page there. The problematic code essentially takes a String dynamically from the server, initializes a variable with that and later uses it as object key. To make the question digestible, I have written a small script:

var bar = "b";
var foo = {[bar]: "Orson oson a borsos borsós fosos koros boros korsón"};

This works under Chrome, FireFox and Microsoft Edge alike, but under IE11, I get the following error:

Expected identifier, string or number

Why is IE11 not allowing this and how should I solve this?

6
  • Maybe the code is ES6 or ES7 related. Try var bar = "b", foo = {}; foo[bar] = "Orson oson a borsos borsós fosos koros boros korsón"; Commented Oct 19, 2016 at 11:39
  • @Mr_Green, that works, but I wonder about the cause my code throws the error. Commented Oct 19, 2016 at 11:40
  • 1
    IE11 supports ES5 but not new versions like ES6 or ES7. In ES5 you can't place a variable in key of object. Hence, the error. Commented Oct 19, 2016 at 11:42
  • Maybe I don't understand what you're trying to do, but why not just doing key = String([bar]) and then use key? Commented Oct 19, 2016 at 11:48
  • 1
    @Ness, that will have no syntax error, but if you console.log(foo); you will see that it has a member called key which should not be there and there is no member called b, which should be there. Commented Oct 19, 2016 at 11:54

1 Answer 1

8

IE11 is old and doesn't support that syntax ... syntactical changes in ES2015+ are not always easy to implement in old tired browsers - though with this you could do

var bar = "b";
var foo = {};
foo[bar] = "Orson oson a borsos borsós fosos koros boros korsón";

using babel, however, the code translates to (ES2015-loose preset)

var _foo;

var bar = "b";
var foo = (_foo = {}, _foo[bar] = "Orson oson a borsos borsós fosos koros boros korsón", _foo);

or (ES2015 preset)

function _defineProperty(obj, key, value) { 
    if (key in obj) { 
        Object.defineProperty(obj, key, { 
            value: value, 
            enumerable: true, 
            configurable: true, 
            writable: true 
        }); 
    } else { 
        obj[key] = value; 
    } 
    return obj; 
}

var bar = "b";
var foo = _defineProperty({}, bar, "Orson oson a borsos borsós fosos koros boros korsón");

This syntax is referred to as Computed property names

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.