Todd Vance
Todd Vance

Reputation: 4711

Javascript shorthand way to assign true/false to variable if a array element exists

I was hoping I could just assign true / false to a variable if my element exists in an associative array.

I tried this --

var finalDisExist = stepsArray['stepIDFinal'];   

-- of course this does exactly what you would think it does (assigning the object to the variable.

But I am pretty sure I have seen something close to this before, can someone tell me what I am missing?

Thanks! Todd

Upvotes: 3

Views: 590

Answers (4)

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340733

Maybe this?

var finalDisExist = !!stepsArray['stepIDFinal'];

The first negation takes everything that was falsy (like undefined and 0) into true and the second one to real false - and vice versa. This means if stepsArray['stepIDFinal'] is equal to null or 0, finalDisExist will be false...

Upvotes: 2

Alexander Pavlov
Alexander Pavlov

Reputation: 32286

Perhaps, the quickest and best way is stepsArray.hasOwnProperty('stepIDFinal').

NB: Do NOT use 'stepIDFinal' in stepsArray, since this will check the entire prototype chain for your "hashmap" object and detect toString among others...

Upvotes: 6

Hacknightly
Hacknightly

Reputation: 5144

You'll want to use stepsArray.hasOwnProperty("stepIDFinal") if I'm not mistaken.

Upvotes: 2

Thomas
Thomas

Reputation: 2162

Do you mean

var finalDisExist = !!stepsArray['stepIDFinal'];

or maybe

var finalDisExist = "undefined" !== typeof stepsArray['stepIDFinal'];

?

Upvotes: 1

Related Questions