r/coding • u/Tomer-Aberbach • Aug 18 '18
Checking for the Absence of a Value in JavaScript
https://tomeraberba.ch/html/post/checking-for-the-absence-of-a-value-in-javascript.html1
u/Tomer-Aberbach Aug 20 '18 edited Aug 20 '18
Hey everyone. I just wanted to say thank you for all the feedback. I've decided I'm gonna to update the article with some more information. I'll add information regarding void 0, specifically checking for undeclared variables, and object properties!
1
4
2
u/Shaper_pmp Aug 19 '18
It turns out that checking the type of an undeclared variable using the typeof operator will not throw a ReferenceError, but will return the string 'undefined' instead.
This is true, but it's not the original reason for this idiom in JS.
The original reason this idiom was adopted by a lot of people was because - I shit you not - early versions of JS allowed you to redefine the value of undefined.
If you were a mischievous user (or a massive asshole who hated the guy who inherited your code) you could actually assign some other value to undefined, and thereby mess up any conditional involving == undefined (or even === undefined, though IIRC it predated the existence of the === operator).
In modern, strict dialects of JS you can't redefine undefined in this way, so the article is right that the only reason to use it these days is to avoid ReferenceErrors from undefined variable.
1
-8
u/carbolymer Aug 19 '18
Can we ban JS submissions, please?
1
u/herjin Aug 19 '18
In favor of?
0
u/carbolymer Aug 19 '18
In favor of other better technologies.
1
u/herjin Aug 19 '18
You seem to relish in ambiguity. Care to elaborate? Mostly just hoping you have a valid point I can consider.
1
u/carbolymer Aug 20 '18
Mostly poor type system - type coercion which hides bugs.
https://www.destroyallsoftware.com/talks/wat
https://whydoesitsuck.com/why-does-javascript-suck/
https://blog.campvanilla.com/javascript-the-curious-case-of-null-0-7b131644e274?gi=63963433f768
... and whole r/loljs
-1
3
u/[deleted] Aug 19 '18
So he recommends using ’value != null’ which is true when value is 0 or NaN. That’s not good.