Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inline if statement and return

I have a function that I'm trying to optimize at the moment but I'm running into some issues.

The function will be called a lot of times, so I'm trying to make it so that the returned value is quickly determined and that the next call begins.

(By quickly determined I mean not having a single return statement at the end of the function.)

This is the simplified code :

function myFunction(letr) {
    if (letr === " ") return var letc = " ";
    // ... other checks on letr that will return other values for letc
}

The issue is that the 2nd line doesn't seem to be valid JavaScript.

How can this be written the right way + optimized ?

Thank you in advance !

like image 235
m_vdbeek Avatar asked Jul 04 '12 02:07

m_vdbeek


2 Answers

Don't declare a variable for the result, just return the value. Example:

function myFunction(letr) {
  if (letr === " ") return " ";
  if (letr === "x") return "X";
  if (letr === "y") return "Y";
  return "neither";
}

You can also use the conditional operator:

function myFunction(letr) {
  return letr === " " ? " " :
    letr === "x" ? "X" :
    letr === "y" ? "Y" :
    "neither";
}
like image 134
Guffa Avatar answered Oct 06 '22 14:10

Guffa


function myFunction(letr) {
    if (letr === " ") return { letc : " " };

    // ... other checks on letr that will return other values for letc
}
like image 29
Alex Avatar answered Oct 06 '22 14:10

Alex