Search code examples
javascriptexpressionvariable-assignmentevaluationtemplate-literals

Expressions in my template literal don't get updated


I define the variable description as a template literal with an expression in it. When I then use description later in runScenario, the expression returns what money started as, not what it currently is.

var money = 100;
var description = `You have ${money} money`;

function payday { 
    money += 50;
}

function runScenario {
    console.log(description);
}

No matter how many times payday is run, the output is always "You have 100 money".

I expected that the expression would be evaluated every time the variable is called, but I'm finding that the expression is only evaluated when defining the variable.

How do I fix this? What could I do instead?


Solution

  • The expression is evaluated instantly, and only once, in your code. You can use an arrow function to apply the template on demand:

    let money = 100;
    const getDescription = () => `You have ${money} money`;
    const payday = () => money += 50;
    const runScenario = () => console.log(getDescription());
    
    runScenario();
    payday();
    runScenario();