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.
Felix kling
source share