Expressions in my template literal don't get updated

60 Views Asked by At

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

There are 2 best solutions below

3
Andrew Parks On BEST ANSWER

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();

0
Shoaib Chikate On

Description variable value is assigned at line 2 hence it won't change although money variable is change

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

function payday { 
    money += 50;
    description = `You have ${money} money`;
}

function runScenario {
    console.log(description);
}

Or create function that will return description

const getDescription = () => `You have ${money} money`;