Date: 2009apr24
Language: javaScript
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>
| What this info useful to you? You can donate to say thanks |
Add a comment
Sign in to add a comment