Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why null is not converted to a boolean value in a conditional statement?

Having the following test case: (find fiddle here)

var a = new Date();
var b = null;
var c = {test: "test"};

if(a)
    console.log(a); //--- prints the current date

if(b)
    console.log('null'); //--- never reached

if(c)
    console.log('test'); //--- prints 'test'

console.log(a && b); //--- prints null

Knowing that

console.log(typeof null); //--- prints "object"
console.log(typeof c); //--- prints "object"

I expect the result of

console.log(a && b); 

to be false and not null as it shown in the example.

Any hint?

like image 785
BeNdErR Avatar asked Dec 29 '25 01:12

BeNdErR


1 Answers

From the MDN:

expr1 && expr2 : Returns expr1 if it can be converted to false; otherwise, returns expr2

new Date can't be converted to false (it's not falsy), so b is returned.

like image 195
Denys Séguret Avatar answered Dec 31 '25 16:12

Denys Séguret



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!