cachaito
cachaito

Reputation: 343

JavaScript and square bracket notation

I am new in Java Script. In both of my books: http://www.larryullman.com/books/modern-javascript-develop-and-design and http://www.packtpub.com/object-oriented-javascript/book both authors are saying that this notation: object[unknownYetProperty] should work when we have object and variable which is objects future property. The problem is two others notation works object['unknownYetProperty'] and object.unknownYetProperty but not first one.

var a1 = 'spring';
var a2 = 'autumn';
var a3 = 'summer';

var object = {
    propertyA1 : a1, // according to books this only this should work :-/
    propertyA2 : a2,
    propertyA3 : a3
}

console.log(object[propertyA1] + ' ' + object['propertyA2'] + ' ' + object.propertyA3);

The working example: http://jsfiddle.net/cachaito/p78Le

Could anyone explain it to me?

Upvotes: 1

Views: 4666

Answers (4)

SrikanthManian
SrikanthManian

Reputation: 148

The property you are accessing using the array notation should be specified as a string.

object['propertyA1']

is the right way to access the property of the object.

Whenever you create an object, the left side of the colon symbol is always a string. Hence, when accessing using array notation, strings should be used for properties.

Upvotes: 1

Salvatorelab
Salvatorelab

Reputation: 11873

Well, when you write this:

object['propertyA1']

Javascript tries to find a property called propertyA1 inside object.

But when you use:

object[propertyA1]

Javascript tries to find a property inside object called... uh, lets see what's inside var propertyA1... WTF? there is no variable with that name!! ok, then propertyA1 is undefined so:

object[undefined]

The difference is that Javascript knows what 'propertyA1' is (a string xD) but when you remove the quotes, that's not a string, that's a variable you have not declared yet.

Upvotes: 1

Andreas Grech
Andreas Grech

Reputation: 107950

The problem with object[propertyA1] is that propertyA1 does not exist.

Basically, it's like doing the following (which doesn't work either): alert(propertyA1);

In contrast with the other two, which correctly reference the fields on your object:

object['propertyA2'] === object.propertyA2 === a2 == 'autumn'

object.propertyA3 == a3 == 'summer'

This is how it would have worked:

var propertyA1 = 'propertyA1',
    temp = object[propertyA1]; // === 'spring'

Upvotes: 4

Jeff Shaver
Jeff Shaver

Reputation: 3355

propertyAl doesn't exist. The reason the string literal and dot notation work is because you are correctly accessing the properties of the object. In the first one, you are trying to access object[undefined] because propertyA1 isn't defined.

Upvotes: 3

Related Questions