Monkey Raptor

Monday, September 7, 2015

JavaScript: Checking Undefined Variable

This already has an answer on Stack Overflow. It's using typeof operator.
As such:

Chrome developer console screenshot

In this tests, there's an undeclared variable called rey

typeof method to check 'undefined'


The recommended method

On JSLint, this method throws error message.

This message:

Unexpected 'typeof'. Use '===' to compare directly with undefined.

To fix that, simply declare the gonna-be-initialized-later variable as a var. Then compare that variable directly with the undefined property using triple equals (===). Or using Boolean negation.

Like so:

On Chrome console:


Links

JavaScript: Checking Undefined Variable
https://monkeyraptor.johanpaul.net/2015/09/javascript-checking-undefined-variable.html

No comments

Post a Comment

Tell me what you think...