× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

How do I check if a variable is defined in JavaScript before I use it?

Rory O'Keeffe
Nov 16, 2016
<p>We've all been there. You try to use a variable, for example <code>foo</code>, and get a console error saying that the variable is undefined.</p> <p>So how do you check for this before you use <code>foo</code>?</p> <pre><code class="language-javascript">if (typeof(foo) !== "undefined") { alert(foo); // foo must be defined! Woo! } else { alert("Houston, we have a problem"); // whoops, you need to define foo... }</code></pre> <p>This is a quick check to make sure that the <strong>type</strong> of <code>foo</code> is not undefined, using the fact that all defined variables have a <em>type,</em> like <code>"string"</code>.</p> <p>This can be useful when consuming API data that may change based on certain conditions, sometimes returning a property and sometimes not. For example:</p> <pre><code class="language-javascript">... // An API call that returns a foo object with unpredictable/unreliable properties if (typeof(foo.theProperty) !== "undefined") { alert(foo.theProperty); // It lives! }</code></pre> <p>Hope that helps!</p>

Get New Tutorials Delivered to Your Inbox

New tutorials will be sent to your Inbox once a week.

comments powered by Disqus