How to check fake using undefined or null?

undefined and null are false in javascript, but

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

but it returns the value of "matters" when trying in the console, why not "null"?

+4
source share
4 answers

To solve your problem:

You can use non-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:

This is considered false or true for Booleans. Therefore, 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
+4
source

You can check the false values ​​using

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

Demo: Fiddle


Or check the veracity, for example

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

Demo: Fiddle

+3
source

, "", , false:

Boolean(null) // false
Boolean(undefined) // false
// but
Boolean("0") // true

:

null == false // not equal, null == true is not equal either
undefined == false // not equal, undefined == true is not equal either
// but
"0" == true // not equal, however, `"0" == false` is equal

, : false, . null Null false Boolean.

, , null undefined .


, , :

if (!value)         // true for all falsy values

if (value == null)  // true for null and undefined

if (value === null) // true for null

, , JS . null, undefined.

+1
source

===checks the identifier - the same type and value. So, null !== falsefirstly, because they are not of the same type, therefore it will not match when used ===.

If you just want to check some falsehood value, then with:

if (!n)

If you want to specifically test null, then check nullas follows:

if (n === null)
0
source

Source: https://habr.com/ru/post/1548301/


All Articles