Jim Jones
Jim Jones

Reputation: 2709

Boolean constructor returns odd data

Why is it in javascript after calling a=new Boolean()

Shouldn't they all be the same?

Upvotes: 0

Views: 53

Answers (3)

reergymerej
reergymerej

Reputation: 2417

The new keyword returns a Boolean object, which is not exactly the same as false.

var a = new Boolean();

// a is a Boolean object
typeof a === 'object';

// using equality operator, a appears to be false
a == false;

// using identity, a is not actually false
a !== false;

// casting your Boolean object results in true,
// similar to casting any other object
Boolean(a) === true;
Boolean({}) === true;

Check out the description from MDN. You'll see that passing an object to Boolean, creates an object with the value true.

The value passed as the first parameter is converted to a boolean value, if necessary. If value is omitted or is 0, -0, null, false, NaN, undefined, or the empty string (""), the object has an initial value of false. All other values, including any object or the string "false", create an object with an initial value of true.

Upvotes: 1

Tibos
Tibos

Reputation: 27853

a = new Boolean()

The [[PrimitiveValue]] internal property of the newly constructed Boolean object is set to ToBoolean(value). See here

This means a is a Boolean object with the primitive value of false (ToBoolean(undefined)).


a == false // true

If Type(x) is Boolean, return the result of the comparison ToNumber(x) == y. See here

ToNumber(a) will be 0 because the primitive value of a is false. 0==false


Boolean(a) // true

When Boolean is called as a function rather than as a constructor, it performs a type conversion. See here

Since a is an object, Boolean(a) will be true. All objects are converted to true.


if (a) doStuff()

The same thing as above, a is an object, so it is coerced to true in an if statement.

Upvotes: 0

MJVDM
MJVDM

Reputation: 3963

The value passed as the first parameter is converted to a boolean value, if necessary. If value is omitted or is 0, -0, null, false, NaN, undefined, or the empty string (""), the object has an initial value of false. All other values, including any object or the string "false", create an object with an initial value of true.

Do not confuse the primitive Boolean values true and false with the true and false values of the Boolean object.

Source, as well as the answer to your questions

Upvotes: 0

Related Questions