Created
August 21, 2018 06:12
-
-
Save LarryBattle/c181c1d9dacca025a11d1bde8c882824 to your computer and use it in GitHub Desktop.
Showing the different types of for loops
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(()=>{ | |
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