Skip to main content

JavaScript: Checking Undefined Variable

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

As such:


Chrome Developer Console Snapshot

In this test, there's an undeclared variable called rey.

typeof method to check 'undefined'


The Other Method

On JSLint, that method above will thrown an error message.

This message:

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

To fix that, simply declare the uninitialised variable with var (or let). Then compare that variable directly with undefined using triple equal (===).

Like so:

Snapshot from Chrome console:


👋

Monkey Raptor uses cookies for analytics, advertisements, and functionality. Privacy Policy