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 !
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";
}
                        function myFunction(letr) {
    if (letr === " ") return { letc : " " };
    // ... other checks on letr that will return other values for letc
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With