2

I am trying to understand what this javascript does and I am looking at foreach and okay, I am guessing name variable is coming from the array. I can verify that from console.log. I can also verify, although I have no idea where it's coming from, that i is 0,1,2.

Can someone please point me to right direction of where this variable 'i' is coming from and how forEach works?

    function getNames() {
       var length = 0
           , names = "";
       ['John', 'Susan', 'Joe'].forEach(function (name,i) {
          length = i + 1;
          names += name + ' '
        })

        return {
            length: length,
            names: names
        }
    }
    undefined
    console.log(getNames());
    Object {length: 3, names: "John Susan Joe "}
    undefined
2
  • 2
    Do you understand where name is coming from, and who is calling that function(name, i) { … } callback? Commented Jul 9, 2015 at 3:28
  • No, I guess I do not.. just guessing it's coming from array but not sure.. digging further and going to read all the comment here.. thanks Commented Jul 9, 2015 at 3:41

3 Answers 3

3

If you look the docs properly it tells

The forEach() method executes a provided function once per array element.

ForEach takes a callback function which can take 3 parameters.

1) Current Value

2) Index of current value // which is 0,1,2

3) Array Itself.

So in following passes value of variables will be as bellow

1) name ==> 'john', i ==> index of 'john' which is 0
2) name ==> 'Susan', i ==> index of 'Susan' which is 1
3) name ==> 'Joe', i ==> index of 'Joe' which is 2
Sign up to request clarification or add additional context in comments.

Comments

2

Any time in JS you see a function that you don't understand, google it on Mozilla Developer Network, like this "mdn forEach". If the function has a $ in it, you might look google it adding "jquery". In this case, though, it is a builtin and so we look it up with mdn. MDN is not the ultimate authority on Javascript, but it is a very good resource as it is maintained by Mozilla, known for their Firefox web browser.

From MDN Array.prototype.forEach

Summary The forEach() method executes a provided function once per array element.

Syntax arr.forEach(callback[, thisArg])

Parameters

  • callback Function to execute for each element, taking three arguments:

    • currentValue The current element being processed in the array.

    • index The index of the current element being processed in the array.

    • array The array that forEach is being applied to.

  • thisArg Optional. Value to use as this when executing callback.

You have ['John', 'Susan', 'Joe'].forEach(function (name,i) so you will see that forEach is being called as a method on the Array ['John', 'Susan', 'Joe']. Here the argument to forEach( ) is an anonymous function with two parameters function(name,i){...}. This function is supplying the callback function mentioned in the docs. That supplied function will get called by forEach as many times as there are elements in the array. The docs say we will get 3 parameters, and in JS the 3rd parameter in this case (the array being modified) is being ignored as the function is written to only take two parameters.

So, matching up the parameters in the provided function with the specification, in this case name is going to be the current value from the array, and i the index number.

Note, though, that what to call the parameters in a function(param1,param2) is completely up to the developer. When reading someone else's code, you have to match up what they called param1 and param2 with what the specification or documentation for that feature says.

1 Comment

Thank you. I really appreciate the answer as not only I understand what this is now(I also altered the variable name and i to something else to verify), but now I am gonna go onto developer.mozilla.org for more information and perhaps read some of these before hand.(these are like perl FAQ).. I accept this as an answer. thank you!
0

How foreach works is it takes a function as its argument. That function is then called for each element of the array with the following arguments function(current_value,current_index,original_array) for example you can do this.

var sumVal = 0,
    sumInd = 0,
    myArray = [2,4,6];

function sumValues(current){
  sumVal += current;
}

function sumIndexes(notGonnaUse,index,o_array){
  sumInd += index;
}

// the following is equivalent to calling sumValues three times
// sumValues(myArray[0], 0, myArray);
// sumValues(myArray[1], 1, myArray);
// sumValues(myArray[2], 2, myArray); 

myArray.foreach(sumValues);

// sumVal is now equal to 2+4+6=12

// the following is equivalent to calling sumIndexes three times
// sumIndexes(myArray[0], 0, myArray);
// sumIndexes(myArray[1], 1, myArray);
// sumIndexes(myArray[2], 2, myArray); 

myArray.foreach(sumIndexes);

// sumIndex is now equal to 0+1+2=2    

In each case the function is passed all three arguments even though sumValues is defined to take only one argument. The remaining arguments can still be accessed using the arguments object. Internally the function is free to call the arguments whatever it wants.

In the previous example we used named functions to pass to foreach, but in your example an anonymous function was passed

function (name,i) {
  length = i + 1;
  names += name + ' '
}

This function sets

name = current value
i = current index

it was also passed in the original array ['John', 'Susan', 'Joe'] as the third argument. Since it wasn't used the programmer didn't bother naming this argument. It can still be accessed however using arguments[2].

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.