'I can't get the value of the variable
I'm learning JavaScript and there is a question that I can't understand:
Consider the given code:
let names = ['ahmed', 'karima', 'hamza','soad'];
let modifiedNames = names.forEach(name => name+99);
The value of modifiedNames here will be?
I am printing the variable in the console but it gives me undefined?!
Thank you in advance.
Solution 1:[1]
You use Array.prototype.forEach which always returns undefined
. Use Array.prototype.map if you want to map your array into a new one.
let names = ['ahmed', 'karima', 'hamza','soad'];
let modifiedNames = names.map(name => name+99);
console.log(modifiedNames);
Solution 2:[2]
Look at the documentation for forEach
:
Return value
undefined.
Therefore modifiedNames
will be undefined
.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Yuriy Yakym |
Solution 2 |