2

I am trying to understand how forEach works in Javascript

var arr = [5,4,3,2,1];

var square = function(x){
   return x * x;
}

arr.forEach(function(item){
     item = square(item);
});

I should get [25, 16, 9, 4, 1]. But get [5, 4, 3, 2, 1]

3 Answers 3

4

item is just an argument to your callback function (that works like a local variable) and modifying it does not change the array - it is not the actual array element. The next two arguments to the callback give you the array and the index so you could modify the actual array element.

var arr = [5,4,3,2,1];

var square = function(x){
   return x * x;
}

arr.forEach(function(item, index, array){
     array[index] = square(item);
});

Working demo: http://jsfiddle.net/jfriend00/L8598/


You may want to note that .map() is made for producing a new array for operations like this:

var arr = [5,4,3,2,1];

var square = function(x){
   return x * x;
}

var newArray = arr.map(square);

Working demo: http://jsfiddle.net/jfriend00/C226B/

Sign up to request clarification or add additional context in comments.

Comments

1

That is because you are not collecting the results in any variable. The variable item is being changed in the local scope of function. To get that result outside you have to collect that in a variable.

Do like bellow

var arr = [5,4,3,2,1];
var result = [];

var square = function(x){
   return x * x;
}

arr.forEach(function(item){
     item = square(item);// 
     result.push(item);
});

Seems like for your above situation map is a better solution

 arr.map(square) //will return expected result.

2 Comments

Don't push to result manually when there's a dedicated function to do this.
@Bergi ya I've told that solution also, but I should tell what is fault with current problem, and how to overcome that.
0

item is a local variable, assigning to it does not alter the array. To modify the array, you'd have to assign to the property arr[i], for example

arr.forEach(function(item, i) {
    arr[i] = square(item);
});

However, what you really want to do is a map that won't modify anything, but produce a new array of the results:

new_arr = arr.map(square);

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.