Last active
April 5, 2023 14:39
-
-
Save DevGW/7cc015a751acec85c37376b66ba80283 to your computer and use it in GitHub Desktop.
Javascript :: .forEach #js
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
let bridges = ['Brooklyn', 'Golden Gate', 'London']; | |
function logUpperCase(string) { | |
console.log(string.toUpperCase()); | |
} | |
bridges.forEach(logUpperCase); | |
// example 1 | |
function whosASpecial(anArrOfPets) { | |
let petString = ''; | |
anArrOfPets.forEach((pet, i) => { | |
petString += `${pet.name} the ${pet.species} is very special!`; | |
if (i !== anArrOfPets.length -1) petString += ' '; | |
}) | |
return petString; | |
} | |
// example 1 deconstructed | |
function whosASpecial(anArrOfPets) { | |
let petString = ''; | |
anArrOfPets.forEach(({name, species}, i) => { // deconstructing pet into name, species | |
petString += `${name} the ${species} is very special!`; // now we dont need pet. | |
if (i !== anArrOfPets.length -1) petString += ' '; | |
}) | |
return petString; | |
} | |
// this: | |
function myForEach(anArr, callback) { | |
let done = anArr.forEach(callback); | |
return done; | |
} | |
// does the same thing as this: | |
function myForEach(anArr, callback) { | |
for (let i=0; i< anArr.length; i++) { | |
let currElem = anArr[i]; | |
callback(currElem, i, anArr); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment