I'm new to JavaScript and so I've been reading a book called Speaking JavaScript. The code below shows how to create a new environment for each function so that the values in each function are isolated. I get the gist of function f() but the last line that invokes function f() is what I don't understand and the author doesn't explain it.
function f() {
var result = [];
for (var i=0; i<3; i++) {
(function () { // IIFE
var pos = i; // Maka a copy of i
var func = function () {
return pos;
};
result.push(func);
}());
}
return result;
}
// Returns 1. I don't understand the reason behind having [1]() after f().
// The syntax looks funny.
console.log(f()[1]());
Thanks in advance.
To break that last line up:
f()
- call the f function. This returns an array, each array element is a function itself.
[1]
- access the second element of the resulting array. Arrays are zero based, so index 0
is first, 1
is second. Square brackets are used to access array elements or object properties.
()
- immediately call the function of the array element we just accessed.