Reputation: 1
I have the following code which seems to work basically fine.
The purpose of the code is to print all names starting with an S (case sensitive), to console.
let names = ['Selma', 'Yirma'];
let sNames = [];
names.forEach( (e)=>{
if (e.charAt(0) === 'S') {
sNames.push(e);
}
console.log(sNames);
});
I used the code in Google chrome console but got "Selma" twice. Why is that? Why not just once?
Upvotes: 0
Views: 2431
Reputation: 1539
Because your console.log() is inside in for loop, Move console.log() outside of the loop.
let names = ['Selma', 'Yirma'];
let sNames = [];
names.forEach( (e)=>{
if (e.charAt(0) === 'S') {
sNames.push(e);
}
});
console.log(sNames);
Upvotes: 0
Reputation: 375
You are seeing Selma twice because in the first iteration of the loop you push it to sNames, then you log sNames, then you log it again on Yirma. So you see Selma twice. Move your console.log outside of the loop.
let names = ['Selma', 'Yirma'];
let sNames = [];
names.forEach( (e)=>{
if (e.charAt(0) === 'S') {
sNames.push(e);
}
});
console.log(sNames);
Upvotes: 1