This javascript:
a.foo != null
really checks if the foo a property is neither undefined nor null . Please note that a.foo? translates to JavaScript that uses != null , not !== null . Transformations that != Mean they are both true:
null == null undefined == null
Simple a? becomes this javascript:
typeof a !== "undefined" && a !== null
because there are three conditions to check:
- Is there
a in scope anywhere? - Does a have
a value of undefined ? - Is
a a null ?
The first condition is important, because simply saying a != null will throw a ReferenceError if there is no a in the area, but typeof a === 'undefined' will not. The typeof check also fulfills the condition a === undefined in 2 . Then we can end it with a rigorous test a !== null , since it takes care of 3 without sacrificing unnecessary performance != (Note != And == slower than !== and === due to implicit conversions).
A little reading about what != And !== can be fruitful:
MDN: Comparison Operators
As for your comment on the remote answer, if(a.foo) is perfectly valid syntax if you populate the if :
if(a.foo) do_interesting_things()
However, if(a.foo) and if(a.foo?) Differ in how they handle 0 , false and '' .
mu is too short Nov 15 '13 at 21:02 2013-11-15 21:02
source share