0

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?

AGamePlayer
  • 7,404
  • 19
  • 62
  • 119

2 Answers2

2

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);
Saadi Toumi Fouad
  • 2,779
  • 2
  • 5
  • 18
1

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);
phentnil
  • 2,195
  • 2
  • 14
  • 22