-1

I am fairly new to js and I have been looking at the Mozilla Developer site. Under the functions section, I can't seem to grasp the following

function map(f,a) {
  var result = [], // Create a new Array
      i;
  for (i = 0; i != a.length; i++)
    result[i] = f(a[i]);
  return result;
}

particulary, this line "result[i] = f(a[i]);"

From Mozilla: Function expressions are convenient when passing a function as an argument to another function. The following example shows a map function being defined and then called with an anonymous function as its first parameter

Can you help explain this?

Here is a link for reference. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions

1

2 Answers 2

0

this piece of code applies to every element of array "a" function "f" and returns the array "result" which contains the results of running function "f" for every element in "a".

Sorry, I've got a recursion :)

Actually it can be used like that:

var array = map(function(val){ return val + 1; },[1,2,3,4,5]);

and in "array" you will have these values:

[2,3,4,5,6]
Sign up to request clarification or add additional context in comments.

7 Comments

There is no recursion there. Unless you pass map as f.
no, the recursion is in my mind :) in the words I've written. In the function there is no recursion at all. Just a joke
But how is "f" a function here when to me it looks like it's a parameter of the map function?
@user3259232 you can send function as parameter of function.
yes, exactly. You can create variables with type function in JS and pass them as parameters
|
-1
result[i] = f(a[i]);

result is an array and the element at index i is being assigned the result of a function call which takes the parameter a[i].

f in the line above is an anonymous function which is parsed into the map function as the first argument. f would be defined somewhere else in code with the following syntax

function(value) {
    return result. 
}

The calling code of your example above would look something like.

var array = map(function(value) { return result; },[1,2,3,4,5]);

I would read up on anonymous functions here which might help. http://en.wikibooks.org/wiki/JavaScript/Anonymous_Functions

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.