function square(number) {
return number * number;
}
square(2); // 4
A simple javascript function codeblock to execute code. Functions have their own local scope and are hoisted, accessible anywhere once defined. Exit out once they hit a return statement.
function pow(x, n) {
if (n == 1) {
return x;
} else {
return x * pow(x, n - 1);
}
}
alert( pow(2, 3) ); // returns to the power of 3 = 8
When a function calls itself.
const func = function(param){
// code here
}
func();
Functions can be assigned to a variable. These functions are anonymous functions. Function expressions are not hoisted and only work after where defined.
function doubleIt(a, b = 2) {
return a * b;
}
console.log(doubleIt(5)); // 10
Parameters take in values to be used in functions. Can also have predefined default parameters.
let truck = {
model: 'Challenger',
maker: 'Dodge',
city: 'Chicago',
year: '2014',
convertible: false
};
const printCarInfo = ({model, maker, city}) => {
console.log(`The ${model}, or ${maker}, is in the city ${city}.`);
};
printCarInfo(truck);
// Prints: The 2014 Challenger, or Dodge, is in the city Chicago.
Functions can use destructuring assignment by using its parameters.
function callbackFunction(){
console.log('Hello');
};
function executeCallback(callback){
callback()
};
executeCallback(callbackFunction);
A callback function is a function passed into another function as an argument.
const doubleIt = (a, b = 2) => a * b;
console.log(doubleIt(5));
Arrow functions provide shorter syntax. Don't require function keyword, return, if returning one line of code, and parentheses, if using only one parameter.
function rollDice() {
return Math.floor(Math.random() * 6) + 1;
}
const dieRoll = rollDice();
If encountered, jumps out of the function and returns given value. Can store and use these values.
Arrow function syntax:
(() => {
// …
})();
Async await syntax:
(async () => {
// …
})();
IIFE's are functions that are immediately invoked function expressions. Runs as soon as it is defined, helps avoid polluting the global scope.