Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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); } });


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'){
  console.log(place.charAt(1), "Is the 2nd char in ", place);

} });


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.