Boolean Mysteries in JavaScript: Why new Boolean(false) Returns True! | JavaScript Tips & Tricks

preview_player
Показать описание
const val = new Boolean (false);

if (val) {
} else {
}

A. 1, boolean
B. 2, boolean
C. 1, object
D. 2, object

======== ANSWER ==========

The correct answer to the code snippet provided is:
C. 1, object

Here's why:
const val = new Boolean(false);
Here, val is assigned a new Boolean object with the value false. However, because it’s created with new Boolean(), val is an object, not a primitive boolean. In JavaScript, any object is truthy, even if it represents false. So val is a truthy object.

if (val)

This line logs the type of val, which is "object", because new Boolean(false) creates a Boolean object, not a primitive boolean.

So, the output of this code is 1 and object.
Рекомендации по теме