Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript Practice forEach in JavaScript Practice forEach forEach Practice - 2

Hamzah Iqbal
seal-mask
.a{fill-rule:evenodd;}techdegree
Hamzah Iqbal
Full Stack JavaScript Techdegree Student 11,145 Points

Why is it that the first Element is returned in forEach loop?

Doing the challenge, I realized that only the first element gets returned.

const days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
let dayAbbreviations = [];





  days.forEach(day => dayAbbreviations = day.substring(0,2));
// dayAbbreviations should be: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa']

Output: "Su"

Also why does it return undefined, if I store the value in this way:

dayAbbreviations =   days.forEach(day =>  day.substring(0,2));
app.js
const days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
let dayAbbreviations = [];





  days.forEach(day => dayAbbreviations = day.substring(0,2));
// dayAbbreviations should be: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa']
// Write your code below

1 Answer

Blake Larson
Blake Larson
13,014 Points

For Each day you want to push the first two letters of the day into dayAbbreviations.

days.forEach(day => dayAbbreviations.push(day.substring(0,2)));

The forEach method actually has no return value so it will always return undefined. Try using .map() instead.