Why is the global variable not updating inside a function?

// my code is

var number = 1;

const override = () => {

var number = 20;

return number;

}

var n = 10;

if (true) {

var n = 20;

}

override();

console.log(number);

console.log(n);

var inside function not updading variables, but inside if scope you can update with var

Your var inside the function is a whole new variable. (This is a function scope variable)

i know it but why it working in IF scope ?

var n = 10;

if (true) {

var n = 20;

} // returns n value 20 but in function not replacing

ah i understand in if scope var replaces n variable, and in function var creates new another variable, yes?

the var keyword makes global variables in general unless the variable is declared in a function. The function scope takes over in this case. (so it is like the global variable you made doesn’t even exist because you declared a new variable inside the function with the same name)

1 Like

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