0

I realize that JavaScript allows both dot notation and bracket notation to create and access object properties. Other than when the property name contains a space or other reserved character or when the property name is a variable in which brackets are required for both scenarios, when should one approach be used over the other? Difference between using bracket (`[]`) and dot (`.`) notation indicates that dot notation should always be used unless there is a specific reason not to. Is this true, and if so, why?

var person={firstname:'John', 'last name':'Doe'};
console.log(person);
person.firstname='Jane';
var nameType='middlename';
//No person.nameType='Sunshine';
person[nameType]='Sunshine';
person['last name']='DoeBo';
console.log(person);

Results:

Object { firstname="John", last name="Doe"}
Object { firstname="Jane", last name="DoeBo", middlename="Sunshine"}
Community
  • 1
  • 1
user1032531
  • 24,767
  • 68
  • 217
  • 387
  • That link doesn't say dot notation should always be used, it just explains when they can be used and the cases in which it will not work and therefor bracket notation must be used. Why could anyone says to use them all the time when they don't work in all cases? The answer you linked is crystal clear already. – GillesC Jul 25 '14 at 12:36
  • I think you misinterpreted that answer. It doesn't matter which form you use, but there are situations where you must use `[ ]`. – Pointy Jul 25 '14 at 12:36
  • 1
    Dot notation is faster, but the square bracket notation allows you to access properties based on variables: `var a = 'foo'; var b = {}; b[a] = 'bar'; console.log(b.foo);` – scragar Jul 25 '14 at 12:36
  • Per referenced post: `Use dot notation: In all other situations.` – user1032531 Jul 25 '14 at 12:40
  • @user1032531: Actually, I think my answer is (currently) slightly-misleading and not really useful. I was about to delete it, would you consider un-accepting it? – T.J. Crowder Jul 25 '14 at 13:20
  • @T.J.Crowder Other than the reasons I listed in my original post, your answer did provide an other reason which was the intent of my question. I have, however, unaccepted it per your request. Thanks for your help. – user1032531 Jul 25 '14 at 17:31
  • @user1032531: Thanks. The thing is, I'm not sure it's correct. :-) Best, – T.J. Crowder Jul 25 '14 at 17:33

0 Answers0