Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript check if value is only undefined, null or false

Other than creating a function, is there a shorter way to check if a value is undefined,null or false only in JavaScript?

The below if statement is equivalent to if(val===null && val===undefined val===false) The code works fine, I'm looking for a shorter equivalent.

if(val==null || val===false){   ; } 

Above val==null evaluates to true both when val=undefined or val=null.

I was thinking maybe using bitwise operators, or some other trickery.

like image 371
Lime Avatar asked Jul 26 '11 21:07

Lime


People also ask

How do you check if a value is not null or undefined in JavaScript?

To check if a variable is equal to null or undefined , use the loose equality (==) operator. For example, age == null returns true if the variable age is null or undefined .

How can I determine if a variable is undefined or null '?

Answer: Use the equality operator ( == ) Therefore, if you try to display the value of such variable, the word "undefined" will be displayed. Whereas, the null is a special assignment value, which can be assigned to a variable as a representation of no value.

How check variable is null or not in JavaScript?

Finally, the standard way to check for null and undefined is to compare the variable with null or undefined using the equality operator ( == ). This would work since null == undefined is true in JavaScript. That's all about checking if a variable is null or undefined in JavaScript.

Is null == undefined?

The undefined value is a primitive value used when a variable has not been assigned a value. The null value is a primitive value that represents the null, empty, or non-existent reference. When you declare a variable through var and do not give it a value, it will have the value undefined.


1 Answers

Well, you can always "give up" :)

function b(val){     return (val==null || val===false); } 
like image 98
hugomg Avatar answered Sep 25 '22 13:09

hugomg