How do you check if a variable is undefined in JavaScript?

← JavaScript answers

For a declared variable use value === undefined; for a variable that might not exist at all use typeof value === "undefined".

let a;
a === undefined;                 // true
 
typeof notDeclaredAnywhere === "undefined"; // true, no ReferenceError
 
value == null;                   // true for both null and undefined
value ?? "fallback";             // use a default for null or undefined

Reading an undeclared name throws a ReferenceError, but typeof is the one operator that is allowed to look at it safely. Reach for == null or the ?? operator when null and undefined should be treated the same.

Related questions

Start debugging smarter today

Try Bugsee for free — no commitments, no hidden fees.

Free sign upLive demoNo credit card required