Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

148
Views
Were I using undefined wrong all these years?

I happened upon something strange (at least to me), and maybe someone can elaborate on this for me:

const a = undefined;
const c = {};

/** this works correctly **/
console.log(a === undefined);

/** this does not throw an exception **/
console.log(c.someProperty === undefined);

/** this throws an exception, why? **/
console.log(b === undefined);

Just is in the example above, why is it, that if I want to check for an objects property, with === undefined which was not defined everything is okay, but as soon as I try to check for a top-level variable for being defined, I am getting an error?

Here's a fiddle.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

The ECMAScript Language Specification states that accessing a nonexistent variable throws a ReferenceError (see GetValue) while accessing a nonexistent property results in undefined (see OrdinaryGet).

To check if a global variable is defined, you can use typeof, which does not throw.

console.log(typeof b === 'undefined');

Top-level variables declared with var also exist on the window object, so you can use a property access too.

console.log(window.b === undefined);
about 4 years ago · Juan Pablo Isaza Report

0

The thing is that b is not undefined, it is not even declared.You cannot call a variable that is not declared, be you can with one that is declared but undefined.

const a = undefined;
const b
const c = {};

console.log(a === undefined) //true
console.log(b === undefined) //true
console.log(c.someProperty === undefined) //true
console.log(typeof d === 'undefined') //true, it does not exist

try{
  console.log(d)
} catch (e) {
  console.log('error!')
} //error!
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!