0

Take the following example:

var obj = {};

obj.test1 = 'string'; // string
obj['test2'] = 'string'; // string
obj['test3'] = ['string']; // array

var key = 'test4';
//obj.key = 'string' // not working

var key = 'test5';
obj[key] = 'string'; // working

console.log(obj);

Fiddle

Why is it possible to access an object property using array notation (square brackets): obj['test2'] = 'string';?

Why does the example at test4 using dot notation fails, but works using array notation at test5?

Sven
  • 12,997
  • 27
  • 90
  • 148

1 Answers1

3

Why is it possible to access an object property using array notation (square brackets): obj['test2'] = 'string';?

Because that's the way JavaScript is defined to work. This isn't "array notation"; it's "square bracket notation".

Why does the example at test4 using dot notation fails, but works using array notation at test5?

obj.key accesses the property on obj that has the name "key". Your object has no property named "key", so this produces undefined.

obj[key] will access the property whose name is the value stored in the variable key. obj['test4'] will access the property with the name "test4" as will obj['te' + 'st4'], and so on.

Square bracket notation allows accessing a property based on a string value. Dot notation allows accessing a property by the name actually written in the code.

JLRishe
  • 99,490
  • 19
  • 131
  • 169