0

I need to know why this isn't working. My Javascript code accesses a variable in an object. But it appears not to be working, partly because I can't figure out the syntax.

    var obj = {
        size:"small",
        big:false,
        thing:true
    }

    alert(obj[size]);

I'm just not sure if I got the syntax right…

user3105120
  • 307
  • 1
  • 3
  • 9

2 Answers2

1

This will work here.

obj.size //returns small

OR

obj["size"] //returns small

OR

var my_var = "size"
obj[my_var]  //returns small
Mritunjay
  • 25,338
  • 7
  • 55
  • 68
  • 2
    Exactly. When you do `obj[size]` it's trying to use the value of a variable called "size" as an index into the object (which is a potentially useful thing to do, but not what you want here). – Jacob Mattison Jul 23 '14 at 14:28
0

You can reference object values either by:

obj["size"]

or

obj.size

However, there is an exception. For instance, if you have following object with a number key: (Note: key is still a string even if it's defined this way):

var obj = {
   1: true
};

You can retrieve it's value only by using: obj["1"]

Hence, using obj.1 will cause a syntax error.

Therefore, your code works if you change it to e.g.: alert(obj["size"]); but I prefer to use console.log(obj["size"]); for debugging. At least, if you are playing with node.js as your tags indicates.

Cheers.

Mauno Vähä
  • 9,688
  • 3
  • 33
  • 54