started the morning with a couple of challenges, these were similar to what we had in ruby fundamentals but now using js
function threeMult(number) {
return number * 3
}
// while loop way
function arrMult(array) {
const result = []
let counter = 0
while (counter < array.length) {
const n = threeMult(array[counter])
result.push(n)
counter++;
}
return result
}
// forEach way
function arrMult(array) {
const result = []
array.forEach(function(num) {
const n = threeMult(num)
result.push(n)
})
return result
}
function even(number) {
return number % 2 === 0
}
function divOrMultTwo(number) {
if (even(number)) {
return number / 2
}
else {
return number * 2
}
}
then we took a deep dive into callbacks
the key takeaway is that we can write functions (in whatever form, in this case they were anonymous) and pass them into another function as an argument, then in that function we can invoke them
function myForEach(func) {
func()
}
myForEach(function() {
console.log("this is an anonymous function")
})
// we're just calling the myForEach and passing in an anonymous function, we can pass in a declarative function if we like
function printHelloDeclarative() {
console.log("this is a declarative function")
}
const printHelloNamed = function() {
console.log("this is a named function expression")
}
myForEach(printHelloDeclarative)
some other notes from the morning
an iffy is an immediately invoked function expression
we can write the anonymous function and put the parenthesis around it straight away
when we write an anonymous function we aren't invoking it, it's just a function without a name
we then looked at a problem to do with setTimeOut
problem was that when we used setTimeOut
we were delaying the math from occurring, code ran asynchronously and returned something we didn't want
we need to use callbacks as a means to allow us to do the math when we return the result
// original
function add(first, second) {
let result = null
setTimeout(function(){
// calculating incredibly long math
result = first + second
}, 2000)
return result
};
console.log(
add(20, 3)
)
// solution with callback
function add(first, second, callback) {
let result = null
setTimeout(function(){
result = first + second
callback(result)
}, 2000)
}
add(20, 3, function(result) {
console.log(result)
})
we then split into js fundamentals
really nice resource for solving the challenges and understanding callbacks
Yeehaw! Cheers, Harrison.