The advantages of object and array literals over using the respective constructors are:
- Shorter and more readable
- Safer: literals will still work when the
Array
or Object
constructors have been overridden
- Possibly faster, though it's unlikely to be a major consideration (any bottlenecks will almost certainly originate elsewhere in code)
In the case of arrays, there's an additional advantage of a literal: it's impossible to create an array with a single member using the Array
constructor alone. For example, [3]
will create an array with one element which is the number 3, while new Array(3)
creates an array of length 3.
Update: the following paragraph is no longer relevant now the question has been edited.
Regarding Booleans, you seem to have a misconception: new Boolean(false)
is not the same as false
. The Boolean()
constructor creates a Boolean object whereas false
and true
are Boolean primitives. In fact, new Boolean(false)
evaluates to true
when coerced into a Boolean in, for example, an if
statement. In short, there's very rarely a reason to use the Boolean()
constructor. Use true
and false
instead. Similarly, other primitives such as strings and numbers have corresponding String()
and Number()
constructors that produce String
and Number
objects that are different to primitive strings and numbers and should generally be avoided.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…