Dave's Brain

Browse - Programming Tips - What's the best way to check if a javaScript variable is defined?

Date: 2009apr24
Language: javaScript
Keywords: is_defined, isDefined

Q.  What's the best way to check if a javaScript variable is defined?

A.  Use tripple equals (exactly equals) operator with "undefined" like this:

<script> var a = [1, 2, 3]; if (a['hello'] === undefined) { alert('UNdefined'); } else { alert('DEFINED'); } </script>
Or you can make a function:
<script> function isArrayElementUndefined(a, element) { return a[element] === undefined; } function isArrayElementDefined(a, element) { return !isArrayElementUndefined(a, element); } function exampleUse() { var a = [1, 2, 3]; if (isArrayElementUndefined(a, 'hello')) { alert('UNdefined'); } if (isArrayElementDefined(a, 'hello')) { alert('DEFINED'); } } </script>

Add a comment

Sign in to add a comment
Copyright © 2008-2017, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.