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
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
string.split('').forEach(...)
works perfectly to iterate over the characters of a string.
However forEach
doesn't return a value, hence result === undefined
.
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
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);
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"; });