skip to Main Content

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


  1. 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`;
    
    function payday() { 
      money += 50;
    }
    
    function runScenario() {
      console.log(getDescription());
    }
    
    runScenario();
    payday();
    runScenario();
    Login or Signup to reply.
  2. 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`;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search