Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Strange new Boolean javascript behavior

can any one explain me this behavior:

if (new Boolean(true)){            
    alert("1");
}else{
    alert("2");
}

must be alert "1", and the response is "1", but

if (new Boolean(false)){            
    alert("1");
}else{
    alert("2");
}

must be alert "2", but the response is "1". Why?,

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

For example:

if (false){            
    alert("1");
}else{
    alert("2");
}

Response "2", and

if (true){            
    alert("1");
}else{
    alert("2");
}

response "1", as we should expect….

>Solution :

That is because objects in JavaScript are true-ish.
When creating a boolean using object creator, new Boolean, you create an object wrapping a boolean value.

You could also see it when doing

const x = new Boolean(false);

console.log(typeof x)

The output will be object. That said, the value of new Boolean(false) is true-ish for the if statement.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading