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 !
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 !
Share Improve this question asked Jul 4, 2012 at 2:05 m_vdbeekm_vdbeek 3,7748 gold badges49 silver badges79 bronze badges 5 |3 Answers
Reset to default 14Don'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
}
Once you return, the function will be terminated and get the value out for the caller
function myFunction(letr) {
var letc = " ";
//Do some thing wit letc;
if (letr === " ") return letr ;
// ... other checks on letr that will return other values for letc
}
return
from a ternary ... :) – Alex Commented Jul 4, 2012 at 2:08return " "
? – hugomg Commented Jul 4, 2012 at 2:09var letc;
outside of the fn 2. Now you can use the 2nd line asif (letr === " ") return (letc = " ");
Encapsulating with parens setsletc
to a single space and returns the single space to the fn's return statement - thusletc === " "
and the fn also returns " " (which would be a truthy result to whatever interprets it.) – gdibble Commented Jan 14, 2017 at 1:48