1

I was wondering if there's any difference between this (property name initializer):

var buffalo = {
    word:"buffalo"
}

and this (string initializer):

var cow = {
    "word":"cow"
}

There seems to be no real difference that I can tell. Is there a specific reason to use one or the other? Or is it just a matter of preference?

Both variables can be accessed using dot syntax or brackets:

alert(buffalo.word+", "+cow.word);      // buffalo, cow
alert(buffalo["word"]+", "+cow["word"]);// buffalo, cow

Thanks for your help!

Frank
  • 2,050
  • 6
  • 22
  • 40
  • 1
    It really doesn't matter honestly. – Joe Sep 18 '15 at 01:05
  • If anyone can direct me to an explanation of why there are two methods, that would be great. Is there a performance benefit to using one over the other? Best practice? Anything? – Frank Sep 18 '15 at 01:07
  • Many coding styles prefer non-quoted keys. –  Sep 18 '15 at 04:24

1 Answers1

0

There is no technical difference. But in terms of readability and maintainability, the . notation is better, because the [] notation is already used for arrays.

The only reason to use the [] notation is if the property name is not a valid variable name, like obj['property-name'].

Mario Pabon
  • 605
  • 4
  • 8
  • 1
    Hey, that's pretty good. Here's a link I found that explains it all in some detail: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects – Frank Sep 18 '15 at 01:30