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!
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.
There is no problem with either syntax, and both will work in all environments. However, by using dot notation where possible, you can save three characters every time.
Source
It is important to remember that JSLint standards are based solely on opinion. Most are usually popular opinion, but some are debatable. That being said, I prefer JSHint instead which allows you to turn off whatever options you don't agree with.
I believe it is to differentiate array elements from object properties and have less confusing code.
For ex:
var x = [];
x.push(stuff);
here x[0]
is how we access it.
var y = { foo: "bar" };
y['foo']
as well as y.foo
work, but to make it clear that foo
is a property of the object y and not an element in the array y, we can use dot notation for objects.