crowhill
crowhill

Reputation: 2558

Javascript: check for key in array that might not exist

Say boundEvents is an array that might or might not exist. If it doesn't exist, then the following code will return 'undefined':

console.log(typeof boundEvents);

Fine. That is exactly what I want. Now say I want to check that theoretical array for the existence of a key which might or might not exist.

console.log(typeof boundEvents['click']);

Uh oh:

Uncaught TypeError: Cannot read property 'click' of undefined

Fair enough, javascript. So let's check to see if the array exists, before we check for the key:

if(typeof boundEvents != 'undefined'){
    console.log(typeof boundEvents['click']);
}

Working again, but I'm wondering if there is a way to eliminate the if statement and just check on the existence of boundEvents['click'] directly, in one step?

Thanks!

EDIT: complete answer, combined from below:

var boundEvents = boundEvents || {};   
console.log(boundEvents.hasOwnProperty('click'));

Upvotes: 0

Views: 67

Answers (3)

chrisvans
chrisvans

Reputation: 248

You can check each layer ending on the variable you want. This will default to undefined if everything is false.

( (typeof boundEvents !== "undefined") && boundEvents['click']) || undefined

Upvotes: 0

crowebird
crowebird

Reputation: 2586

If you want an explicit true / false then:

(boundEvents || {}).hasOwnProperty('click')

Upvotes: 1

Daniel Conde Marin
Daniel Conde Marin

Reputation: 7742

You can do:

boundEvents = boundEvents || {};
console.log(boundEvents['click']);

or in a single line:

console.log((boundEvents || {})['click']);

Upvotes: 2

Related Questions