'Why the variable in a setTimeout function can't access the window.global_varible correctly using the = || way?
Here is the code:
window.test1 = 'Jack';
setInterval(function(){
console.log(test1); // Works fine, expect output: "Jack"
}, 2000);
Refresh the window and enter:
window.test1 = 'Jack';
setInterval(function(){
var test1 = test1 || [];
console.log(test1); // Works bad, get [] instead of "Jack"
}, 2000);
Why is this happening?
Solution 1:[1]
Why is this happening?
It's because of variable hoisting
so this
window.test1 = 'Jack';
setInterval(function(){
var test1 = test1 || [];
console.log(test1); // Works bad, get [] instead of "Jack"
}, 2000);
is actually this
window.test1 = 'Jack';
setInterval(function(){
// declaring local variable test1 and it has no value so it holds `undefined`
var test1;
// so now you gett [] instead because the variable test1 is falsy `undefined`
test1 = test1 || [];
console.log(test1); // Works bad, get [] instead of "Jack"
}, 2000);
Solution 2:[2]
This is happening because you are declaring the test1 variable within the function and variable hoisting. Using your example and a modified version, we can see that the first timeout function shows the same result we expect and that one way to avoid this problem is the example in the second timeout function (using a different variable descriptor):
window.test1 = 'Jack';
setTimeout(function() {
var test1 = test1 || [];
console.log('timeoutFunction1', test1); // Works bad, get [] instead of "Jack"
}, 2000);
setTimeout(function() {
var test2 = test1 || []; // Works fine since we're not declaring `test1` in this function
console.log('timeoutFunction2', test2);
}, 3000);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Saadi Toumi Fouad |
| Solution 2 | phentnil |
