Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript function returns undefined when using ternary statement [duplicate]

Tags:

javascript

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/

like image 517
Bobby Kotzev Avatar asked May 24 '26 18:05

Bobby Kotzev


1 Answers

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)?

like image 114
Daniel A. White Avatar answered May 26 '26 08:05

Daniel A. White