Created
May 29, 2020 05:27
-
-
Save harrisonmalone/282aa82ac2ca0e2fe3788a68d7ff5910 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// what is a callback function in js? | |
[1, 2, 3].forEach((v, i) => { | |
console.log(v) | |
}) | |
const myFunc = (cb) => { | |
return cb(10) | |
} | |
const result1 = myFunc((num) => { | |
return num * 10 | |
}) | |
console.log(result1) | |
// => 100 | |
function adder1(x, y, callback) { | |
let answer = x + y; | |
// => 3 | |
if (callback) { | |
return callback(answer); | |
} | |
return answer; | |
} | |
function shoutSomething(answer) { | |
return answer | |
} | |
const result2 = adder1(1, 2, shoutSomething); | |
console.log(result2) | |
// => 3 | |
const invokeCallback = (cb) => { | |
console.log('2') | |
const result = cb(10) | |
// => 100 | |
console.log('4') | |
return result | |
} | |
const adder2 = (number) => { | |
console.log('3') | |
return number * number | |
// => 100 | |
} | |
console.log('1') | |
console.log(invokeCallback(adder2)) | |
console.log('5') | |
// => 100 | |
// --- | |
const arr = [1,2,3] | |
// own custom forEach | |
// yield | |
Array.prototype.myForEach = function(cb) { | |
// .forEach | |
// what does forEach do? | |
// while | |
const len = this.length | |
let index = 0 | |
while(index < len) { | |
cb(this[index], index) | |
index += 1 | |
} | |
console.log("###") | |
} | |
// custom to me | |
arr.myForEach((item, index) => { | |
console.log(`The item is ${item}`) | |
console.log(`The index is ${index}`) | |
console.log(`------`); | |
}) | |
// built into the language | |
arr.forEach((item, index) => { | |
console.log(`The item is ${item}`) | |
console.log(`The index is ${index}`) | |
console.log(`------`); | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment