There are two reasons:
forEach completely ignores the value you return from its callback
You never do anything to update value
If you want to modify value, you'd either do this:
value = value.map(element => element + 2);
...which creates a new array and assigns it to value; note that b is completely unaffected. (This is just like your value += 2 in the other branch, which also doesn't affect b at all.) Live example:
const b = [1, 2, 3, [4, 5], 6];
b.forEach((value, index) => {
if (Array.isArray(value)) {
value = value.map(element => element + 2);
}
else {
value += 2;
}
console.log(`The value at ${index} is ${value}`);
})
// Just to show that `b` is unaffected:
console.log(`b[3] = ${b[3]}`);
Or this:
value.forEach((element, index) => {
value[index] = element + 2;
});
...which changes the original array (inside b), which doesn't match the else branch (which doesn't update b). Live example:
const b = [1, 2, 3, [4, 5], 6];
b.forEach((value, index) => {
if (Array.isArray(value)) {
value.forEach((element, index) => {
value[index] = element + 2;
});
}
else {
value += 2;
}
console.log(`The value at ${index} is ${value}`);
})
// Just to show that `b` is modified:
console.log(`b[3] = ${b[3]}`);
But, if you want to modify b, you should probably do it consistently. Kobe posted how you'd do that with map, which creates a new array and is often what you want. If you wanted to update the existing array instead, then:
const b = [1, 2, 3, [4, 5], 6];
for (const [bIndex, value] of b.entries()) {
if (Array.isArray(value)) {
for (const [vIndex, entry] of value.entries()) {
value[vIndex] = entry + 2;
}
} else {
b[bIndex] = value + 2;
}
}
console.log(`b = ${JSON.stringify(b)}`);
...but Kobe's map solution is usually what I'd reach for unless I had a good reason to update in place.
b[0]to be 1 or 3? (Not the output, the value inbafter the loop has completed.)b[0]to still equal 1.