Why use {} instead of new Object() and use [] instead of new Array() and true/false instead of new Boolean()?

后端 未结 5 1108
南方客
南方客 2020-12-06 00:55

Many people say that you should avoid new Object, new Array()and instead use {}. [], and true/false.

What are the benefits of using the literal constructs to get a

5条回答
  •  星月不相逢
    2020-12-06 01:43

    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.

提交回复
热议问题