JS: Variables in global scope are treated like closures. Why?

In the following code,

var price = 14
var quantity = 3
var total = price * quantity
price = 15
console.log(`total is ${total}`)

total is called after price is updated however total still has access to old value of price.

This statement var total = price * quantity is not inside a closure so it has access to the updated price = 15
value then why does not use that instead uses the initial value of price?


That’s because there are two types of variables, primitive and object.
Numbers are primitive, so it’s going to be just as is calculated at the time.

You can instead use a function so that it calculates things as they are at the time instead.

function total() {
    return price * quantity;
1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.