JavaScript undefined replaced with null
Solution 1
The abstract equality algorithm from section 11.9.3 of the language spec is what defined ==
and !=
and it defines them such that
null == void 0
null == null
void 0 == null
where void 0
is just a reliable way of saying undefined
(see below) so the answer to your question is yes, null
is equal to undefined and itself and nothing else.
The relevant parts of the spec are
1. If Type(x) is the same as Type(y), then If Type(x) is Undefined, return true. If Type(x) is Null, return true. ... 2. If x is null and y is undefined, return true. 3. If x is undefined and y is null, return true. ...
If you're worried about undefined
meaning something other than what it normally means, use void 0
instead.
null == void 0 // True
({}).x === void 0 // True
"undefined" === typeof void 0 // True
(function () {})() === void 0 // True
(undefined = 42,
undefined === void 0) // False
"undefined" === typeof undefined // False
"undefined" === typeof void 0 // True
From the language specification:
11.4.2 The void Operator
The production UnaryExpression : void UnaryExpression is evaluated as follows:
- Let
expr
be the result of evaluating UnaryExpression/.- Call
GetValue(expr)
.- Return undefined.
So the void
prefix operator evaluates its argument and returns the special value undefined regardless of to what the global variable undefined
has been changed (or whether undefined
is defined :).
EDIT: In response to comments,
If you are dealing with library code that distinguishes between the two, then you need to deal with the difference. Some of the new libraries standardized by the language committee do ignore the difference : JSON.stringify([void 0]) === "[null]"
but there is too much code out there that treats them subtly differently, and there are other differences :
+(null) === 0
isNaN(+undefined)
"" + null === "null"
"" + undefined === "undefined"
If you're writing any kinds of libraries that produce text or serialize/deserialize and you want to conflate the two then you can't pass undefined
through and expect it to behave as null
-- you need to explicitly normalize your inputs to one or the other.
Solution 2
Because of this:
var myVar1;
var myVar2 = null;
if (myVar1 === null) alert('myVar1 is null');
if (myVar1 === undefined) alert('myVar1 is undefined');
if (myVar2 === null) alert('myVar2 is null');
if (myVar2 === undefined) alert('myVar2 is undefined');
Anything set to null is not undefined - it's defined as null.
Lime
https://www.toptal.com/php/a-utf-8-primer-for-php-and-mysql https://gist.github.com/mwunsch/4710561 How does GitHub detect whether the browser has color emoji support? Detect emoji support - xpath CSS SQL https://pastebin.com/raw/8c9RJW70 https://stackoverflow.com/q/32981319 https://stackoverflow.com/q/15305852 Pass arguments to a scriptblock in powershell jQuery for java - jsoup gwtquery Development Environments - eclipse, netbeans, visual studio, intellij Call Java function from JavaScript over Android WebView How to open layout on button click (android) style & themes https://developer.android.com/reference/packages.html How can we view webpages in our android application without opening browser? http://www.ezzylearning.com/tutorial/customizing-android-listview-items-with-custom-arrayadapter Best way to reorder items in Android 4+ ListView In Android, how can I set the value of a edit box in WebView using Javascript What does WISC (stack) mean? How to create custom view from xml-layout? Create View-Object from XML file in android Java http://chat.stackoverflow.com/transcript/message/35730032#35730032 How do I "decompile" Java class files? Is there something like python's interactive REPL mode, but for Java? Is there a package manager for Java like easy_install for Python? Hyperpolymorph, Hyperpolyglot, https://certsimple.com/rosetta-stone Lisp | A Replace Function in Lisp That Duplicates Mathematica Functionality | Lisp Interpreter How to change XAMPP apache server port? xampp MySQL does not start http://es6-features.org/ react-native phonegap https://cordova.apache.org/ http://en.cppreference.com/w/c/types/integer ModernC autoit mouserecorder What are the maximum number of arguments in bash? Maximum number of Bash arguments != max num cp arguments? Maximum string length node.js and python? IE For Linux https://developer.mozilla.org/en/docs/Web/API/Touch_events JavaScript for detecting browser language preference
Updated on July 28, 2022Comments
-
Lime almost 2 years
In JavaScript
undefined
can be reassigned, so it is often advised to create a self executing function that assures undefined is actually undefined. As an alternativenull
andundefined
are definitely==
but are any other values loosely equivalent tonull/undefined
?TLDR
Basically can you safely replace this:
(function(undefined){ window.f = function(obj){ if(obj===undefined || obj===null ){ alert('value is undefined or null'); } } })();
with:
window.f = function(obj){ if(obj==null){ alert('value is undefined or null'); } }
If the above is 100% safe, why doesn't the JavaScript community/libraries drop
undefined
altogether and use the shorterx == null
conditional to check for bothnull
/undefined
at once?EDIT:
I have never seen someone actually represent an "unknown value" with 'undefined' vs
null
? I have never seen this scenario, and is why I originally asked the question. It just appears to be two incredibly confused values that are never used in their original intent. Standardizing everything to do a comparisonobj==null
would be beneficial for size and avoid any issues with reassignment. Everything would continue to workvar obj={}; obj.nonExistantProperty==null // true var x; ix==null // true function(obj){ obj==null // true }
The one exception to this rule appears to be when casting
undefined
/null
to an integer. This is a pretty age case scenario, but definitely should be noted.+(null)==0
whileisNaN(+undefined)
Considering NaN is the only value in JavaScript not equal to itself, you can do some pretty crazy things like:
+undefined == +undefined // false +null == +null // true
Using
null
as a loose equality==
drop in replacement forundefined
is safe, provided you don't plan to cast the value to an integer. Which is a pretty edge case scenario. -
Lime almost 13 yearsMy point is there appears to be no value in distinguishing between the two. Although
undefined
is supposed to represent an "unkown value", nobody actually holds to this convention. -
Brian almost 13 yearsAssuming you never assign anything to a value of undefined, there's value in being able to differentiate between an untouched variable and a nullified one. Though, for all pratical purposes in how JS is used by developers today, I can see your point...
-
Lime almost 13 yearsYou could just as easily use
null
in the code above as usingvoid 0
. I could also argue thatnull
is slightly easier to read and type thenvoid 0
. My point is there appears to be no value in distinguishing between the two. Although undefined is supposed to represent an "unkown value", nobody actually holds to this convention. So it would appear beneficial to ignoreundefined
every existed and just useobj==null
in its place. -
Lime almost 13 yearsThanks, I wasn't aware of what the values were when casted to integers. Having
NaN
vs0
is definitely different. It appears[null].join('')
and[undefined].join('')
are equivalent though. -
Lime over 8 yearsThe last one is horrendous