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 JavaScript Array Iteration Methods Array Iteration Examples Using forEach()

Position of things inside array

const places=['Melbourene','sydney',,'Merryland','Queensland','Manly','Australia']; let newArray=[]; places.forEach(place=>{ if (place.charAt(2)==='M'){ newArray.push(place); } });

console.log(newArray);

This code does not work.Its almost same as i am trying to make newArray starting from Alphabet M.But, when i change the position of the array to 0 that is first one it works again as Melbourne is at the first

if (place.charAt(0)==='M')

Why does this happen???????

1 Answer

Jeffrey James
Jeffrey James
2,636 Points

So what the charAt function refers to is the nth character (zero based indexing) of location which is being called in the forEach method.

var places = ['Melbourene','sydney','Merryland','Queensland','Manly','Australia']; 
var newArray = []; 

places.forEach(place =>{ if (place.charAt(0)==='M'){
  newArray.push(place); 
  console.log(place.charAt(1), "Is the 2nd char in ", place);

} });

console.log(newArray);

I added a console log to hopefully convey the point of what the charAt method is doing. The method is implemented on the string in this case. In your case, I don't think any of the locations have "M" as their 3rd character.

Thank you so much..I cleared the issue.