Sunday, May 31, 2015

Java if vs. Javascript if.

Not all if's are created equal. In Java, you really have to detail exactly what you want to check for. If you put anything inside of an if that's not a boolean comparison, you get an error. Since everything starts out as null, you spend most of your time in Java checking for null (myVar != null).

List<Object> myList = new ArrayList<>();
//This line will throw an ERROR incompatible types required: boolean found: List<Object>
if(myList){//basically you need a boolean expression inside the if...
}
if(myList != null){//works fine because checking against null returns a boolean
//do stuff
}
//the one trick you can do, is to check for a truthy boolean
boolean bool = true;
if(bool){
//this code will get run even without checking for (bool == true)
}
view raw JavaIf hosted with ❤ by GitHub
However, in Javascript, you can do all kinds of fun things with an if!

var x;
if(x){
//this will not run because x is undefined, (kind of like null in Java)
}
x = null;
if(x){
//this will not run because x is null, even though it is defined
}
x = true;
if(x){
//this will run, because x is defined AND true
}
x = false;
if(x){
//this will NOT run, because although x is defined, its value is still false
}
view raw JavaScriptIf hosted with ❤ by GitHub
Clearly the JavaScript if is doing more than simply evaluating boolean expressions. It inherently checks for undefined, null, "", 0, NaN, or false, as well as the classic uses of an if.
This begs the question... Why can't the Java if be more like the JavaScript if? Thousands of checks for null could be removed if the Java if inherently checked for null when presented with a Object.

No comments:

Post a Comment