JavaScript - Sample Interview Question (Senior Level)

What will be the result of the following script?

function createList(list) {
    var result = [];
    for (var i = 0; i < list.length; i++) {
        var item = 'item' + list[i];
        result.push( function() {alert(item + ' ' + list[i])} );
    }
    return result;
}

function foo() {
    var list = createList([1,2,3]);
    for (var j = 0; j < list.length; j++) {
        list[j]();
    }
}

foo();

  1. It will alert:
    item1 1
    item2 2
    item3 3
  2. Run time error - you can not push functions into array
  3. It will alert:
    item3 undefined
    item3 undefined
    item3 undefined
  4. Run time error - result is not initialized properly (using new array)
Tests in JavaScript for Seniors

Test Name Difficulty Time (minutes) No. of Questions
JavaScript Online Test for Seniors JavaScript Senior 60 30

More Specific Tests in JavaScript for Seniors

Test Name Difficulty Time (Minutes) No. of Questions
JavaScript-Advanced Online Test for Seniors JavaScript - Advanced Senior 20 10
JavaScript-Object-Oriented Online Test for Seniors JavaScript - Object Oriented Senior 20 10
JavaScript-Algorithms Online Test for Seniors JavaScript - Algorithms Senior 20 10