Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
154
rated 0 times [  160] [ 6]  / answers: 1 / hits: 22196  / 11 Years ago, wed, june 19, 2013, 12:00:00

What is the real difference in using [] and . for accessing array or object properties? Which one to use?



Also why doesn't . operator allow the index property?


More From » syntax

 Answers
11

Accessing members with . is called dot notation. Accessing them with [] is called bracket notation.



The dot notation only works with property names which are valid identifier names [spec], so basically any name that would also be a valid variable name (a valid identifier, see also What characters are valid for JavaScript variable names?) and any reserved keyword [spec].



Bracket notation expects an expression which evaluates to a string (or can be coerced to a string), so you can use any character sequence as property name. There are no limits to what a string can contain.



Examples:



obj.foo;  // valid
obj.else // valid, reserved keywords are valid identifier names
obj.42 // invalid, identifier names cannot start with numbers
obj.3foo // invalid,
obj.foo-bar // invalid, `-` is not allowed in identifier names

obj[42] // valid, 42 will be coerced to 42
obj[--] // valid, any character sequence is allowed
obj[bar] // valid, will evaluate the variable `bar` and
// use its value as property name





Use bracket notation:




  • When the property name is contained in a variable, e.g. obj[foo].

  • The property name contains characters not permitted in identifiers, e.g. starts with a digit, or contains a space or dash (-), e.g. obj[my property].



Use dot notation: In all other situations.



There is a caveat though regarding reserved keywords. While the specification permits to use them as property names and with the dot notation, not all browsers or tools respect this (notably older IE versions). So the best solution in my opinion is to avoid using reserved keywords for property names or use bracket notation if you cannot.






†: That's also the reason why you can only use bracket notation to access array elements. Identifiers cannot start with digits, and hence cannot consist only of digits.


[#77548] Monday, June 17, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mira

Total Points: 460
Total Questions: 108
Total Answers: 99

Location: American Samoa
Member since Fri, Aug 26, 2022
2 Years ago
mira questions
;