Checking if a value exists in Javascript

How to prevent Javascript warning if warning value is undefined? In other words, something like this:

if (alert(message) != 'undefined') { alert(message); } 
+6
javascript jquery
source share
1 answer

Use typeof :

 if (typeof message !== 'undefined') 

Do not put alert(message) in the if expression, otherwise you will execute alert (which we want to avoid before we learn the message type) and the return value (which is also undefined btw;)) will be compared to undefined .

Update Explanation for !== :

This operator not only compares the value of two operands, but also the type . This means that the type of enforcement is not executed:

 42 == "42" // true 42 === "42" // false 

In this case, this is not necessary, because we know that typeof always returns a string, but it is good practice, and if you use it carefully and consistently, it is more clear where you really want to have type coercion and where not.

+10
source share

All Articles