This is my first attempt to write shorthand if statements however am befuddled by why the expanded versions don’t work quite the way I imagined they would.
Code 1 – Does not work
if(document.getElementById == true) {
alert("The document object model is supported by: " + navigator.appName);
}
Code 2 – Does work
if(document.getElementById != false) {
alert("The document object model is supported by: " + navigator.appName);
}
Code 3 – The shorthand that does work
if(document.getElementById) {
alert("The document object model is supported by: " + navigator.appName);
}
Why is that if I expand the shorthand in 3 to the first code sample not work and why does it work if I have it equal to != false?
Your first
ifstatement:…doesn’t work because
document.getElementByIdis a function, which is a type of object, and an object is not equal totrue.Your second
ifstatement:…doesn’t really work – even though you think it does – because (I’m assuming) you’ve only tested it in a browser where
document.getElementByIdis defined in which case, again,.getElementByIdis a function, a type of object, which not equal tofalse. But, if.getElementByIdis not defined then the if test will effectively be testing ifundefined != falsewhich is alsotrue. So that test isn’t doing what you think it is.Your third
ifstatement:…does work. The reason it works is because JavaScript has the concept of “truthy” and “falsy” expressions. The number 0, the empty string
"",undefined,null,NaN, and of coursefalseare all “falsy” values. Pretty much everything else, including non-zero numbers, non-empty strings, and any objects (including functions) are “truthy”. If the expression in theifstatement is “truthy” then the if block will be executed.(Finally, there really isn’t any need to test whether
document.getElementByIdexists – I’d be amazed if you can find a browser that runs JS but doesn’t define that method.)