Why You Should Never Use `x==null` in ExtendScript
May 13, 2020 | Tips | en
The Japanese scripter あるふぁ found a bug affecting any ExtendScript code based on ...==null
. This is not a critical issue (because experienced developers never use such condition!) but the case provides the opportunity to summarize important rules regarding falsey values and the equality operator…
(Updated 13 May, 2020.) In ExtendScript, the expression 0 == null
is true (although it is false in JavaScript—thanks to Martin Kraetke for pointing out my original mistake.) Now give a try to this code:
var x = 0; alert( x == null ); // What did you expect?
In ExtendScript CS4 to CC, the result is false, which is a very deceitful bug. Indeed, since 0 == null
and x=0
, it should obviously follow that x == null
.
So the scripting engine eventually makes a difference between a literal value (0
, ""
, NaN
, undefined
, etc.) and a variable pointing out to that very value. Digging further, we found that the problem specifically concerns null
tests.
The bug affects the equality operator (==
), not the strict equality (===
).
Anyway, what we can get out of this is a well-known rule: the ==null
test never makes sense in ExtendScript.
• Want to know if something is falsey? Use !something
.
• Want to know if it is strictly null? Use something===null
.
• Want to know if it is undefined? Use 'undefined'==typeof something
.
Note. — In JavaScript, the NULL test is used to check whether something is either null
or undefined
, disregarding other falsey values. I didn't even notice this crucial difference, which makes ExtendScript and JavaScript totally discordant. This sounds like another good reason to avoid == null
.