3

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/

2 Answers2

4

JavaScript has semicolon insertion after return. You should put an expression after it so that it can continue.

You can read up on the rules here: What are the rules for JavaScript's automatic semicolon insertion (ASI)?

Community
  • 1
  • 1
Daniel A. White
  • 174,715
  • 42
  • 343
  • 413
0

In first case after "return" there is nothing to evaluate on the same line. In this case the function returns "undefined". This is how this language works.

Try this:

function test1(a,b)
{
  return a && a == 1 && b && b.match(/abc/i) ? 
      a + 1 : 
      0;
}
Antoan Elenkov
  • 556
  • 1
  • 4
  • 13