6

How do I prevent a Javascript alert from firing if the alert value is undefined? In other words, something like this:

if (alert(message) != 'undefined') { alert(message); } 

1 Answer 1

10

Use typeof:

if (typeof message !== 'undefined') 

Don't put alert(message) into the if expression, otherwise you will execute alert (which we want to avoid before we know the type of message) and the return value (which is also undefined btw ;)) will be compared to undefined.

Update Clarification for !==:

This operator not only compares the value of two operands but also the type. That means no type coercion is done:

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

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

Sign up to request clarification or add additional context in comments.

1 Comment

Note how Felix used the !== operator instead of !=. Douglas Crockford explains this (and other awesome JS facts) here: video.yahoo.com/watch/630959/2974197

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.