Maykel
Maykel

Reputation: 175

how to obtain values from forEach javascript

I've always used array.forEach(element=>console.log(element) to see what I am obtaining from array; but now I want to obtain the values themselves.

Suppose I have the following code:

array=['1','2','3','4']

array.forEach(x=>x)//undefined

What I want to obtain is :

'1'
'2'
'3'
'4'

is this the correct approach or there is some other way I am not seeing right now?

Upvotes: 0

Views: 65

Answers (1)

jfriend00
jfriend00

Reputation: 707696

array.forEach() presents each value to your callback one at a time. That's how it works and to use that, you put code into the callback that does something with the values.

As an example:

let array = [1,2,3,4];

let product = 1;

array.forEach(x => {
    console.log(x);
    // update the product variable
    product *= x;
});

console.log(product);

If you're trying to do array.forEach(x, ...) in the console, then you see undefined because array.forEach() has no return value (and thus undefined).


Other array functions such a .map(), .filter(), .reduce(), etc... all have return values, and you can pick one of them depending upon what type of operation you're trying to do on the array.

For example, the previous code block, could have been written with .reduce()

let array = [1,2,3,4];

let product = array.reduce((total, x) => {
    console.log(x);
    return total * x;
}, 1);

console.log(product);


And, here's an example of .map() that returns a new array with every value squared:

let array = [1,2,3,4];

let product = array.map(x => {
    return x ** 2;
}, 1);

console.log(product);

Upvotes: 3

Related Questions