Skip to content

Instantly share code, notes, and snippets.

@omarbenmegdoul
omarbenmegdoul / everyExplainer.js
Last active March 27, 2021 01:11
someArray.every(callback) explainer
//This program will take an array of numbers and return true if they're all divisible by 3, else false.
//.every is used for obtaining a boolean -- not an array -- if every element passes a condition
//So there is a final variable that stores the boolean output (therefore we need a return)
//another way to explain it: every() returns true when filter() would return the same array
//we can use the "arrow function" shorthand to rewrite the function definition in a shorter way
let baseArray = [1,2,3,4,5,6,7,8,9,0];
let finalBoolean = true; //just declaring this variable for later
finalBoolean = baseArray.every(
@omarbenmegdoul
omarbenmegdoul / filterExplainer.js
Last active March 27, 2021 01:09
someArray.filter(callback) explainer
//This program will take an array of numbers and return the ones that can be divided by 3.
//.filter is used for obtaining a second array with only the elements that pass a CONDITION
//So there is a final array where the results have to be stored.
//We can use the "arrow function" shorthand to rewrite the function definition and save space.
let baseArray = [1,2,3,4,5,6,7,8,9,0]
let finalArray = baseArray.filter(
num => (num % 3 === 0) //what goes on the other side of the arrow is the condition
)
@omarbenmegdoul
omarbenmegdoul / forEachExplainer.js
Created March 27, 2021 01:07
someArray.forEach(callback) explainer
//This program will log all elements in an array to the console.
//forEach is used for DOING something with each element of an array.
//Notice that we're not trying to produce a value: we're not getting back a modified array or even a single value at the end. There is no output, just logging.
//If you want, you can define the function directly inside the `baseArray.forEach(callback)` call. Literally cut and paste.
let baseArray = [1,2,3,4,5,6,7,8,9,0];
baseArray.forEach(
function logger(someMessage) {
console.log(someMessage); //this is the DOING something part
@omarbenmegdoul
omarbenmegdoul / mapExplainer.js
Last active March 27, 2021 01:04
someArray.map(callback) explainer
//This program will take an array of numbers and return an array of those numbers to the power of 3.
//map is used for transforming each element of an array to receive a new array.
//So there is a final array where the results have to be stored.
//We can convert translate the function to the arrow function shorthand to save space
let baseArray = [1,2,3,4,5,6,7,8,9,0];
finalArray = baseArray.map(
num => num ** 3 //what goes on the other side of the arrow is what would go after "return" in the old function
)