D
D
denver2014-06-14 11:29:01
JavaScript
denver, 2014-06-14 11:29:01

What's not kosher about the if (!item.x) check?

Ran diagonally across: stackoverflow.com/questions/135448/how-do-i-check-... but the question remains unclear.

There are several ways to check that the var item = { foo: 'bar' } object does not contain the x key:

if (!item.x)
if (!item['x'])
if (typeof item['x'] === 'undefined')
if (!('x' in item)) // кошерно
if (!item.hasOwnProperty('x')) // кошерно (плюс исключает наследуемые x)

What's wrong with the first two. Are there browsers that will generate a notice, or can it return something unexpected, and what are those possible surprises?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Victor, 2014-06-14
@denver

If item.x is 0, an empty string, false, or anything else that evaluates to false, the condition will yield !false == true, even though the x key actually exists.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question