Junior
Milliseid tagajärgi võib kaasa tuua muutuja deklaratsioon kasutades var funktsiooni sees?
sobes.tech AI
Vastus AI-lt
Variable declaration with var inside a function has function scope. This means such a variable is accessible throughout the entire function, ignoring block scopes (for example, inside if or for).
Consequences:
- Variable overwriting: A variable declared with
varin a block can overwrite a variable with the same name declared earlier in the same function but outside this block. - Hoisting: The declaration of a variable with
varis hoisted to the top of the function. This means you can use the variable before its declaration, but its value at the time of use will beundefined. - Unexpected behavior in loops: In
forloops with asynchronous operations (likesetTimeout), a variable declared withvarwill have the last value from the loop for all asynchronous callbacks, not the value at the iteration moment.
Example of hoisting and overwriting:
function exampleVarScope() {
console.log(a); // undefined (due to hoisting)
var a = 10;
if (true) {
var a = 20; // Overwrites the outer variable 'a'
console.log(a); // 20
}
console.log(a); // 20 (value from the `if` block)
}
exampleVarScope();
Example with loop and asynchronous operations:
function varLoopExample() {
for (var i = 0; i < 3; i++) {
setTimeout(function() {
console.log(i); // Will output 3, 3, 3 (i has the last value from the loop)
}, 100);
}
}
varLoopExample();
Due to these features, it is recommended to use let or const, which have block scope, to prevent unforeseen situations.