Search code examples
javascriptoptimizationdesign-patterns

How to use disposable variables in JavaScript?


I want to set a variable based on the result of a function call.. I don't want to call the function two times, or add an unncessary "temporary" variable to the function scope. I know it's probably premature optimization but I like doing that.

I can use the temporary variable obj inside a block scope like this:

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 order to do that, I have to make output a let which is.. wrong. It won't change value, so I want it to be a const.

The only way I know how to achieve this involves calling the function multiple times, like this:

const output = get_object().x > get_object().y ? "x is greater than y" : get_object().x < get_object().y ? "etc";

So is there another way I can calculate the value of output with temporary variables? Something like this:

const output = (const obj = get_object(); obj.x > obj.y ? "x is greater than y" : obj.x < obj.y ? "etc");

Solution

  • Your use of let is the clearest way to do it, IMHO. There's no way to declare a variable that can be assigned only once and must remain read-only after that.

    If you really want to use const, you could do it with ternaries in the initialization expression.

    function foo() {
      const obj = get_object();
      const output = obj.x > obj.y ?
        "x is greater than y" : (
          obj.x < obj.y ?
          "x is less than y" : "x is equal to y"
        );
      console.log(output);
    }

    If the initialization requires even more complex logic, you could use an IIFE.