Checking if an array key exists in a JavaScript object or array

For the sake of completeness, you can use the in operator. This is probably the best way to check for missing keys.

	var hi = {hello: "world"};
	alert( hi["hello"] );      // popup box with "world"
	alert( hi["goodbye"] );    // popup boc with "undefined"
	
	// this works even if you have {"goodbye": undefined}
	if( "goodbye" in hi ) {
	    // do something
	}

By Keenlio, June 3, 2014

What do you think?

Leave a Reply

Your email address will not be published. Required fields are marked *


+ 5 = nine

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>