Check if key exists or not in a JavaScript array

7 July, 2008 (22:59) | JavaScript/AJAX | By: Rohan Shenoy

Since I work with PHP as well as JavaScript, I know that there is no easy in-built function in JS to check if a given key exists or not in a JavaScript array object. Google-ing for the same returned some user-made functions that were either too long and complicated or even impractical with huge arrays.

The below small snippet works just fine:

[-]View Code JAVASCRIPT
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<script type="text/javascript">
//lets setup a sample array and its key-and-values
var array=new Array();
array['name']='Rohan Shenoy';
array['gender']='Male';
array['age']='21';
 
//lets try to find an key which exists
if(array['name']==undefined)
{alert('That key is undefined');}
else
{alert('That keys exists');}
 
//lets try to find an key which does NOT exist
if(array['residence']==undefined)
{alert('That key is undefined');}
else
{alert('That keys exists');}
</script>

As simple as that!

Write a comment