Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to check falsy with undefined or null?

undefined and null are falsy in javascript but,

var n = null;
if(n===false){
console.log('null');
} else{
console.log('has value');
}

but it returns 'has value' when tried in console, why not 'null' ?

like image 600
Navin Rauniyar Avatar asked Jul 14 '14 05:07

Navin Rauniyar


2 Answers

To solve your problem:

You can use not operator(!):

var n = null;
if(!n){ //if n is undefined, null or false
console.log('null');
} else{
console.log('has value');
}
// logs null

To answer your question:

It is considered falsy or truthy for Boolean. So if you use like this:

var n = Boolean(null);
if(n===false){
console.log('null');
} else{
console.log('has value');
}
//you'll be logged null
like image 182
Bhojendra Rauniyar Avatar answered Sep 23 '22 00:09

Bhojendra Rauniyar


You can check for falsy values using

var n = null;
if (!n) {
    console.log('null');
} else {
    console.log('has value');
}

Demo: Fiddle


Or check for truthiness like

var n = null;
if (n) { //true if n is truthy
    console.log('has value');
} else {
    console.log('null');
}

Demo: Fiddle

like image 44
Arun P Johny Avatar answered Sep 24 '22 00:09

Arun P Johny