Given two JS functions which implement the same exact logic, the first (test1) will always return undefined while the second one (test2) will return the expected value. The implementation difference is a single return statement, vs storing the evaluated value in a local variable and then returning it.
Why does test1 return undefined instead of the expected result? Secondary, why storing it in a local variable (test2) makes it work?
Here is the exact example:
function test1(a,b)
{
return
a && a == 1 && b && b.match(/abc/i) ?
a + 1 :
0;
}
function test2(a,b)
{
var val =
a && a == 1 && b && b.match(/abc/i) ?
a + 1 :
0;
return val;
}
alert(test1(1,'abc')); // returns undefined when it should return 2
alert(test2(1,'abc')); // returns 2 as expected
Here is a JSFiddle to it: https://jsfiddle.net/8gmn004t/1/