Dave's Brain

Browse - programming tips - javascript is defined

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
Copyright © 2008-2012, 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.
Advertisements: