Reputation: 3229
I've seen numerous threads about bracket vs dot notation when accessing objects....however I'm going through freeCodeCamp and when I'm accessing an object with a syntax such as SomeonesName['online']
it will suggest I should use dot notation instead?
Besides being quicker.....what exactly is the benefit? Everything I've seen minus "speed" seems to imply bracket notation is better?
Is there something I'm missing? perhaps another thing that the "dot" operator does better?
Upvotes: 2
Views: 2075
Reputation: 1
I would say use which ever one your more comfortable with. Just be consistent. I used codeacademy, and sometimes your code will be correct, but freeCodeCamp my looking for a specific way for you to do it in order to move to the next lesson. hope this helps
Upvotes: 0
Reputation: 8497
The rule of thumb is very simple. Everytime you can use dot notation, use it. You only need to use bracket notation when you have to manipulate invalid JavaScript identifiers or when you need to pass a variable key. Consider this example:
var obj = {
foo: "Foo",
_bar: "Bar",
$baz: "Baz",
"foo-bar": "Foo Bar",
quux: "Quux"
};
console.log(obj.foo);
console.log(obj._bar);
console.log(obj.$baz);
console.log(obj['foo-bar']);
var quux = "quux";
console.log(obj[quux]);
Values can be retrieved from an object by wrapping a string expression in a [ ] suffix. If the string expression is a string literal, and if it is a legal JavaScript name and not a reserved word, then the . notation can be used instead. The . notation is preferred because it is more compact and it reads better.
Douglas Crockford, JavaScript: The Good Parts
Upvotes: 4
Reputation: 182
. & [] both notations are functionally same and no difference in execution speed. The difference is only when the accessing key having some special characters which conflicts in javascript while accessing the property.
Upvotes: 1
Reputation: 9427
The two following lines are functionally identical in javascript;
SomeonesName.online
SomeonesName["online"]
You only really need to use square brackets if you are accessing a key with a name that is invalid (such as one containing a .
or -
) or if you are using a variable.
Otherwise, the dot notation is nicer to read and write, and most linters and programmers prefer it.
In regards to your edit - they are both functionally identical. They take the same amount of time to run, and with the right IDE they can even take the same amount of time to write. It's purely a matter of preference. There is no benefit apart from style consistency.
Upvotes: 3
Reputation: 68933
.
Dot notation is faster to write and clearer to read. []
Square bracket notation allows access to properties containing special characters and selection of properties using variables.
Please go through for details: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Property_accessors
Upvotes: 3