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

Why doesn't this work?

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

// dayAbbreviations should be: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'] // Write your code below

dayAbbreviations = days.forEach(day => day.slice(0, 1));

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

// dayAbbreviations should be: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa']
// Write your code below

dayAbbreviations = days.forEach(day => day.slice(0, 1));

1 Answer

forEach attempts to perform an action on each iteration of the array, but it unfortunately cannot return an array itself. If you run this in the console, you'll see that it returns undefined

Your solution attempts to set dayAbbreviations equal to a JS function that will return undefined.

For the solution, you don't actually need to set dayAbbreviations equal to anything. You'll actually want the action preformed on each iteration of forEach to append the sliced string to the dayAbbreviations list.

An additional tip: when you slice(x, y) x = 0-based starting position y = 0-based position to end before (basically, this number is non-inclusive)

So you'll actually want slice(0, 2)