0

What is wrong with this:

  var a = "1";
  var b = {};
  var b[a] = 'test';

According to this SO question, the above is valid. But var b[a] = 'test' is generating this error in AngularJS (v1):

Uncaught SyntaxError: Unexpected token [

2
  • 8
    Remove the var from the third line and it'll be the same as that question. Commented Feb 21, 2017 at 13:58
  • DOH! I was staring right at it. Commented Feb 21, 2017 at 14:10

1 Answer 1

6

This line:

var b[a] = 'test';

is not valid, because the characters [ and ] are not allowed in variable names.

If you are not wishing to declare a new variable on that line, but rather just assign a key/value pair to the object b, you can just remove the var:

b[a] = 'test'; //b now equals { "1": "test" }
Sign up to request clarification or add additional context in comments.

1 Comment

Yep, I actually see stuff like this somewhat often among beginners. var is only required for declaring/"create" a new variable. While b[a] doesn't currently exist, it's not a variable; it's a property of an object belonging to the variable b. In the same manner, you don't need var when assigning a value to an existing var, e.g. a = 2;.

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.