DEV Community

Discussion on: You don't need null

Collapse
 
martinpham profile image
Martin Pham

Btw it’s fun when

  • Access a variable which is not defined: we have ReferenceError
  • Access an attribute which is not defined: no error, it returns undefined
 
loucyx profile image
Lou Cyx • Edited

Yup, it kinda sucks, but is preferable to return undefined for something that isn't defined ... you can still check if a variable exists before trying to access it, by using typeof:

console.log(foo); // ReferenceError
console.log(typeof foo !== "undefined" ? foo : "Nope"); // "Nope" 🎉
Enter fullscreen mode Exit fullscreen mode

Accessing properties is a better DX, and with ?. and ?? is even better:

const obj = {};
console.log(obj?.foo ?? "Nope"); // "Nope" 🎉
Enter fullscreen mode Exit fullscreen mode
 
martinpham profile image
Martin Pham

I’m not talking about the check. I’m just trying to point the inconsistency between two cases about the same thing.

 
loucyx profile image
Lou Cyx

But that's the thing, they aren't the same thing. One is trying to access something not declared in the scope, while the other is trying to access a property of something that is declared in the scope. You can test both with typeof === "undefined", but if you try to access something undeclared you get an error, which sucks, but that's how it works. Nowadays is very difficult to end up in this scenario tho, because editors will let you know if you're trying to access an undeclared value.

Some comments have been hidden by the post's author - find out more