I've been linting some of my code and got some errors back saying it is better to use dot notation. I found out I was using square bracket notation (with clarity from this great post), however, I wanted to ask why exactly does Crockford prefer dot notation? The project I'm working on has used SBN for it's entirity, and I don't think it's confusing or un-readable, but if there are distinct reasons to user dot, I will correct it.
Just want to understand it fully before proceeding!
Dot notation is faster to write and easier to read than bracket notation. However, you can use variables with bracket notation, but not with dot notation. This is especially useful for situations when you want to access a property but don't know the name of the property ahead of time.
The dot notation is used mostly as it is easier to read and comprehend and also less verbose. The main difference between dot notation and bracket notation is that the bracket notation allows us to access object properties using variable.
Dot notation is one way to access a property of an object. To use dot notation, write the name of the object, followed by a dot (.), followed by the name of the property. Example: var cat = { name: 'Moo', age: 5, }; console.
We must use bracket notation whenever we are accessing an object's property using a variable or when the property's key is a number or includes a symbol or is two words with a space.
As I best understand Crockford, I think it comes down to consistency and avoiding the use of reserved words. On his site, he states:
The dot notation can be used when the subscript is a string constant in the form of a legal identifier. Because of an error in the language definition, reserved words cannot be used in the dot notation, but they can be used in the subscript notation.
Since you can refer to reserved words in subscript notation, it could cause confusion. Basically, avoid using reserved words as the names of your object's members. The dot notation enforces this (through the language -- an error as Crockford calls it), and so it would be considered a better coding practice to avoid using reserved words.
Also on the same site, he also states that the dot notation is "a little more convenient".
From "JavaScript: The Good Parts" it says on page 21:
The . notation is preferred because it is more compact and it reads better.
The book is written by Douglas Crockford himself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With