user2630764 user2630764 - 2 months ago 8
Javascript Question

Object literals in [] notation in javascript

I have two examples . In the first example :

a.
1. var object = {1 : "value"};

alert(object[1]);

2. var object = {1 : "value"};

alert(object["1"]);


In both of the examples , the output is "value". I read in the books that object[1] will find a variable
1
and substitute the value with that.
Since 1 cannot be declared as variable name in javascript
(var 1="some var" //not allowed)
, is it just
alert(object[1])
tries to find the string declared in
var object = {1 : "value"};
and alerts "
value
".

Because , there is no difference between 1. and 2. example alerts yield the same result.

b.
1.
var object = {a : "value"};

alert(object["a"]);

The above example is pretty much clear that it is finding out string "a".

2.
var object = {a : "value"};

alert(object[a]);


The above example is an error , since we havent declared

var a = "some";


I am just curious to know the difference between a. 1 and a.2 and also if my understanding is correct wrt these examples?

Answer

In both of the examples , the output is "value". I read in the books that object[1] will find a variable 1 and substitute the value with that.

No. It takes a string.

If you pass it a number literal, it converts the number to a string.

If you pass it a string literal, it uses the string literal as a string.

If you pass it an variable then it gets the value of that variable and converts it to a string if it isn't already one.

1 is not a variable name. The grammar of JavaScript requires that it be treated as a number literal.

I am just curious to know the difference between a. 1 and 2

In case 1, you are passing a number literal. In case 2, you are passing an undeclared variable. You get a ReferenceError when you try to get a value from an undeclared variable.

You'd get the same effect in any other context where you were doing something with a value.

var foo = 1; // Assigns 1
var foo = bar; // Throws a reference error because bar is undeclared
Comments