Is there a way to set a variable based on the result of a function call without calling the function multiple times or adding unnecessary temporary variables? Even though it might be seen as premature optimization, I prefer to avoid that.
One approach is to use a block scope with a temporary variable obj
:
function foo(){
let output;
calculate_output: {
const obj = get_object();
if(obj.x > obj.y){
output = "x is greater than y";
}else if(obj.x < obj.y){
output = "x is less than y";
}else{
output = "x is equal to y";
}
}
console.log(output);
// more code that uses [output] below, so I don't want an unnecessary [obj] cluttering the function scope here..
}
But in this case, making output a let
might not be ideal since it won't change value. It should ideally be a const
.
However, trying to achieve this usually involves calling the function multiple times:
const output = get_object().x > get_object().y ? "x is greater than y" : get_object().x < get_object().y ? "etc";
So, is there a better way to calculate the value of output
with temporary variables without compromising on performance?
const output = (const obj = get_object(); obj.x > obj.y ? "x is greater than y" : obj.x < obj.y ? "etc");