Skip to content

Instantly share code, notes, and snippets.

@DevGW
Created December 29, 2022 13:44
Show Gist options
  • Save DevGW/df0bd0858f87bd92711c6497f87525ef to your computer and use it in GitHub Desktop.
Save DevGW/df0bd0858f87bd92711c6497f87525ef to your computer and use it in GitHub Desktop.
Javascript :: PBV v. PBR Functions
// Pass By Value vs. Pass By Reference
// callbacks: passing functions into other functions
function functionLogger(callback, argument) {
console.log('Function starting');
const result = callback(argument);
console.log('Functioncomplete');
return result;
}
// writing a function using the expression method:
let happyFunction = function () {
console.log("I am happy!");
}
happyFunction() // <--- calling the function
>I am happy!
////////////////////////////
// calling functions stored in arrays
function happyFunction() {
console.log('I am happy!');
}
let amazingArray = [happyFunction, happyFunction, happyFunction];
for (let i = 0; i < amazingArray.length; i++) {
let element = amazingArray[i];
element();
}
>I am happy!
I am happy!
I am happy!
////////////////////////////
// you can pass in a function as a parameter into another function
function firstFunction(anotherFunction) {
anotherFunction(); // invoke a function
}
function saysHi(name) {
console.log('Hi', name);
}
function saysBye(name) {
console.log('Bye', name);
}
function callsWithName(name, sayHiOrBye) {
sayHiOrBye(name);
}
callsWithName('Sadie', sayssHi);
callsWithName('Sadie', saysBye);
>Hi Sadie
>Bye Sadie
// passing in an anonymous function when you don't need a name, just instructions
// the second parameter passed is the entire function
sayToAll(group, function (name) {
console.log("Hello, " + name + "!");
})
// callback example
function finderFunction(anArr, callback) {
for (let i=0; i < anArr.length; i++) {
let currElem = anArr[i];
if (callback(currElem)) return i;
}
return -1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment