2

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.

bvh
  • 443
  • 4
  • 10

3 Answers3

2

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.

MrCode
  • 63,975
  • 10
  • 90
  • 112
0

Function f is returning an array which has the values 0, 1, 2:

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);

So, to show you an example of the working code, the author wants to print to the console, but cannot just call f as the array will need to know what index to display, so he has added index position 1 so the array knows which record inside of it you would like to see.

If you wanted to print out the entire array to console, you would need to loop through the array, calling each index of the array.

So to summarize:

f returns array
console.write will write to console
[1] is the index
and f()[1] is the position of the array to display
Lemuel Botha
  • 659
  • 8
  • 22
  • It's not returning an array with values [0,1,2]. It returns an array of 3 functions, each when invoked will return 0,1,2 respectively, and that's the whole point and the sophisticated expression f()[0](). this answer is not correct. – Lzh Dec 06 '14 at 15:36
0

The function f returns an array of functions, each of which returns their index position in the array.

This is just a shorthand way of first invoking f() to get the array, then getting the function at index 1, f()[1], and then invoking that function to get the final result, f()[1]().

devdigital
  • 34,151
  • 9
  • 98
  • 120