Skip to content

Instantly share code, notes, and snippets.

@LarryBattle
Created August 21, 2018 06:12
Show Gist options
  • Save LarryBattle/c181c1d9dacca025a11d1bde8c882824 to your computer and use it in GitHub Desktop.
Save LarryBattle/c181c1d9dacca025a11d1bde8c882824 to your computer and use it in GitHub Desktop.
Showing the different types of for loops
(()=>{
const myFriends = [
{ name: "Bob", age: 20},
{ name: "Jane", age: 18},
{ name: "Mary", age: 16},
];
const checkAges = (friends, ages) => {
ages.forEach((age, i) => {
const friendsAge = friends[i].age;
if(friendsAge !== age){
throw new Error(`Wrong age:{age} at index: ${i}. ${friendsAge} !== ${age}`);
}
});
}
const forLoop = (friends) => {
const ages = [];
for(let i = 0; i < friends.length; i++){
ages.push( friends[i].age );
}
return ages;
};
const forInLoop = (friends) => {
const ages = [];
for(let i in friends ){
ages.push( friends[i].age );
}
return ages;
};
const forOfLoop = (friends) => {
const ages = [];
for(let friend of friends ){
ages.push( friend.age );
}
return ages;
};
const forEachLoop = (friends) => {
const ages = [];
friends.forEach( friend => {
ages.push( friend.age );
});
return ages;
};
checkAges( myFriends, forLoop(myFriends) );
checkAges( myFriends, forInLoop(myFriends) );
checkAges( myFriends, forOfLoop(myFriends) );
checkAges( myFriends, forEachLoop(myFriends) );
console.log("Ages check out good");
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment