Some Javascript interview questions.


1. What should be the output of the following code snippet.


const arr = [1, 2, 3, 4];
for (var i = 0; i < arr.length; i++) {
  setTimeout(function() {
    console.log('Index: ' + i + ', element: ' + arr[i]);
  }, 4000);
}

Output : 
Index: 4 ,  element: undefined

Explanation :
Actually the setTimeout function will create a closure function which have access to the upper local variable i . So once the for loop gets executed the setTimeout function is get executed and the i value goes up . So within this 1 sec the i value goes upto 4 and the arr[4] value would be undefined .

Comments

Post a Comment

Popular posts from this blog

The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters.

The transaction is aborted or Failure while attempting to promote transaction.

Unable to load one or more breakpoints in Visual studio.