Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why don't I pass any parameters to a function within map?

How come we do not have to pass an argument to function b in the code below? Is it just because we are using map method of type Array? Or is there anywhere else that we can use a function just like this in JavaScript?

Can someone give a very clean and through explanation?

Code:

/* we have an array a*/
const a = ['a', 'b', 'c'];
/*we define a function called b to process a single element*/
const b = function(x){do something here};
/*I noticed that if we want to use function b to take care with the 
elements in array a. we just need to do the following.*/
a.map(b);
like image 817
red_Coder Avatar asked Mar 05 '18 06:03

red_Coder


1 Answers

Functions are first class citizens in Javascript, which is just a fancy way of saying they can be passed around as variables and arguments.

What you are doing when you call

a.map(b);

Is essentially calling

[
  b('a'),
  b('b'),
  b('c')
]

The array function map just calls the given function (in your case b), with each argument in the array, and puts the output in a new array. So there are arguments being passed to b, it's just that map is doing it behind the scenes for you.

As for your other questions, there are plenty of cases where you'll pass a function as an argument without calling it first. Another common function is the Array object's reduce.

const out = a.reduce(function (accumulator, val) {
  return accumulator + ' - ' + val;
}
// out: 'a - b - c'

Also a lot of functions take callbacks, that are called when some kind of asynchronous task is completed. For instance. setTimeout, will call a given function after the elapsed time.

setTimeout(function (){
    console.log("Hello World!");
  }, 1000
);
// Will print "Hello World!" to console after waiting 1 second (1000 milliseconds).

And you can easily write your function to take another function as an argument too! Just call the function you've passed in as you would any other function.

// A really basic example
// More or less the same as [0, 1, 2].map(...)
function callThreeTimes(f) {
  return [
    f(0),
    f(1),
    f(2)
  ]
}

// My function here returns the square of a given value
function square(val) { return val * val }

const out = callThreeTimes(square);
// out: [0, 1, 4]
like image 183
SCB Avatar answered Nov 10 '22 13:11

SCB