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 new instance of an Object or Array rather than using new? I konw that Crockford doesn't like new but is that the main argument?
{} is shorthand for creating an empty object. You can consider this as the base for other object types. Object provides the last link in the prototype chain that can be used by all other objects, such as an Array . [] is shorthand for creating an empty array.
The comparison operator ==, when used with objects, checks whether two objects are the same one. Since there are two {} in the statement {} == {}, two new objects are created separately, and then they are compared. Since they are not the same object, the result is false.
It is shorthand for empty array. Same as new Array(). Also {} is an empty object. Objects are like hashtables in Js so you can use it as a dictionary. Copy link CC BY-SA 2.5.
The valueOf() method returns the primitive value of a Boolean object.
The advantages of object and array literals over using the respective constructors are:
Array
or Object
constructors have been overriddenIn 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.
For example, if you want to do this:
{name:"bla",address:"address"}
the new Object() way would be:
var o = new Object();
o.name="bla";
o.address="address";
The first one is much shorter. And I think that it would be faster in many browsers, too (jsperf testcase).
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