-1

I was reading here on stack overflow that these are not equal. So what is the difference.

What happened is that in 2nd case value was assigned as the property of myObj. So if b='abc'; then myObj.abc was now available.

I had always thought same thing but [] version was used when name were weird ones.

Qantas 94 Heavy
  • 15,750
  • 31
  • 68
  • 83
Muhammad Umer
  • 2,228
  • 2
  • 18
  • 17
  • Syntax, but you need to use `[]` when names have special characters that can not be using in the dot format. Aka parameter names with dashes, periods, etc. – epascarello Jun 25 '13 at 17:41
  • 2
    [working with objects](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects). – Denys Séguret Jun 25 '13 at 17:42
  • 1
    duplicate of [JavaScript property access: dot notation vs. brackets?](http://stackoverflow.com/questions/4968406/javascript-property-access-dot-notation-vs-brackets) and [Different behavior when using dot-notation vs. bracket-notation](http://stackoverflow.com/questions/4234777/javascript-different-behavior-when-using-dot-notation-vs-bracket-notation) – Bergi Jun 25 '13 at 17:45

3 Answers3

4

Dot notation takes an identifier that is the property name. The square bracket notation accepts a string representation of the property name.

Given var a = "a"; then myObj.a = b and myObj[a] = b and myObj["a"] = b are equivalent.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • thanks i think i learned this way back but didnt have to use brackets till now. Let me know if i am right. Brackets are also used for method/property names that dont start with strings like this `obj.['9'] = {};` – Muhammad Umer Jun 26 '13 at 03:56
  • so if i do this basically whole program crashes: `Object.prototype[4]={};` – Muhammad Umer Jun 29 '13 at 22:19
0

a lot, results would depends on a var value. but ["a"] would be the same as .a

Edorka
  • 1,781
  • 12
  • 24
0

The difference between myObj.a=b and myObj[a]=b is that in the first case you are accessing an attribute called a in the object. In the second you are accessing an attribute whose name is in a variable called a.

On the other hand, myObj.a=b and myObj["a"]=b would be equivalent.

Joni
  • 108,737
  • 14
  • 143
  • 193