0

I'm practicing the forEach() construct on simple letter array. I want to convert letters to uppercase and print them to the console. So I've made it work, when I put the console.log() inside the callback function. But why on earth it isn't possible to put the console.log() outside the callback function. It gives an undefined error

This works:

var letters = [ "a","b","c"]; 

var capitalize = function (element,index,array) {

    console.log(element.toUpperCase());

};


letters.forEach(capitalize);

this doesn't work: (it gives undefined)

var letters = [ "a","b","c"]; 

var capitalize = function (element,index,array) {

    return element.toUpperCase();

};


console.log(letters.forEach(capitalize));
3
  • What language are you coding in? Commented Oct 8, 2015 at 14:34
  • 2
    forEach doesn't return anything. You should try .map or explicitly insert a return statement. E.g. return element.toUpperCase(); Commented Oct 8, 2015 at 14:37
  • doesn't work either.. see adjusted code in initial post Commented Oct 8, 2015 at 14:39

2 Answers 2

1

What you want is map()

var letters = [ "a","b","c"]; 

var capitalize = function (element,index,array) {
    return element.toUpperCase();
};

console.log(letters.map(capitalize));
Sign up to request clarification or add additional context in comments.

4 Comments

Ok, this is indeed the answer... but I don't get it can you please explain why console.log(ARRAY.forEach() don't work and console.log(ARRAY.map() works
this will create a new array
It's because foreach doesn't return anything, it just provides a way to iterate through an array and do things. You're not changing assignment of any of the array elements, you're just calling toUpperCase() on each element but not doing anything. map() is meant to return a newly "mapped" array of elements. The function you provide returns the "transformed" array element and pushes it into a new array to be returned once done looping through everything.
the fonction foreach transform your array and return nothing while map creates and return the new array containing the transfomed values.
0

forEach() executes the callback function once for each array element; unlike map() or reduce() it always returns the value undefined and is not chainable.

Source

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.