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?
2
Answers
The expression is evaluated instantly, and only once, in your code. You can use an arrow function to apply the template on demand:
Description variable value is assigned at line 2 hence it won’t change although money variable is change
Or create function that will return description