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 [

Community
  • 1
  • 1
lilbiscuit
  • 2,109
  • 6
  • 32
  • 53

1 Answers1

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" }
hackerrdave
  • 6,486
  • 1
  • 25
  • 29
  • 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;`. – Quangdao Nguyen Feb 21 '17 at 14:11