-2

In Javascript, why is result below undefined?

var x = "happy";
var result = x.split('').forEach(function(val,index,array){
   array[index] = "0";
}); 
console.log(result); 

The output is:

undefined
Gary
  • 51
  • 1
  • 7
  • `forEach` doesn't return anything. You'll want to use `map`. – Bergi Jan 22 '16 at 23:25
  • @Bergi it's unclear that he actually wants a new array, he appears to be trying to modify it in-place. – Alnitak Jan 22 '16 at 23:25
  • did the question subject get updated to add the `var result = ` bit? – Alnitak Jan 22 '16 at 23:27
  • @Alnitak: Given that he just created the array using `split`, his intention seems to be getting a new array in a one-liner. Which is exactly what `map` is supposed to do. The attempt to modify anything in-place is just a side show. – Bergi Jan 22 '16 at 23:32
  • Thank you all! I think my confusion came from thinking that if `split` returns something, then it doesn't matter if `forEach` returns something. The difference between `forEach` and `map` is also useful. – Gary Jan 22 '16 at 23:32

4 Answers4

2

string.split('').forEach(...) works perfectly to iterate over the characters of a string.

However forEach doesn't return a value, hence result === undefined.

Alnitak
  • 334,560
  • 70
  • 407
  • 495
1

Because forEach is editing the array in place. It doesn't return an array. Your code works with this modification:

var x = "happy";
var result = x.split('');
result.forEach(function(val,index,array){
   array[index] = "0";
}); 
console.log(result); 

forEach() executes the callback function once for each array element; unlike map() or reduce() it always returns the value undefined and is not chainable. The typical use case is to execute side effects at the end of a chain. - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach#Description

Joseph Marikle
  • 76,418
  • 17
  • 112
  • 129
1

As stated forEach does not return a value.

You can use map()

var x = "happy";
var result = x.split('').map(function(val,index,array){
   return "0";
}); 
console.log(result); 
epascarello
  • 204,599
  • 20
  • 195
  • 236
0

This is because forEach iterates over the array. It doesn't return anything.

Try this:

var x = "happy";
var result = [];
x.split('').forEach(function(val,index,array){
  result.push("0");
});

console.log(result);

With underscorejs you could write it with two lines:

var x = "happy";
var result = _.map(x.split(''), function(el){ return "0"; });
guitarman
  • 3,290
  • 1
  • 17
  • 27