I mentioned earlier that functions in JavaScript behave like strings or numbers. In particular, you can make an array consisting of functions. Let's do:
let arr = [
function() {console.log('1')},
function() {console.log('2')},
function() {console.log('3')},
];
Let's, for example, print the contents of the zero element of the array to the console:
let arr = [
function() {console.log('1')},
function() {console.log('2')},
function() {console.log('3')},
];
console.log(arr[0]); // we'll see the source code of the first function
As you can see, in the example above, we get the source code of the function, not the result.
In order for a function to be called, parentheses
must be added to it. Since our function is stored
in arr[0]
, the parentheses will need to be
written after the square brackets,
like this: arr[0]()
. Let's check:
let arr = [
function() {console.log('1')},
function() {console.log('2')},
function() {console.log('3')},
];
arr[0](); // shows '1'
You can also iterate over our array with functions in a loop and call each of the functions in this loop:
let arr = [
function() {console.log('1')},
function() {console.log('2')},
function() {console.log('3')},
];
for (let func of arr) {
func(); // invokes our functions in a loop
}
Make the array arr
with three
functions. Let the first return through
return
the number 1
, the
second - the number 2
, the
third - the number 3
.
Using the array arr
you've created,
print the number 3
to the console
by calling the corresponding function.
Using the array arr
you've created,
find the sum of the results of the
functions work (without the loop).
Loop through the arr
array you
created and output the results of all
functions work to the console.