functions(){
}
The confusing world of functions in JavaScript
Basic function declaration
function myFunk () {
// do all the things...
}
myFunk(); // does all the things
# JS FUNCTIONS
Function with argument
function myFunk (argument) {
// do all the things to argument...
}
myFunk("bananas"); // does all the things to bananas
myFunk(7); // does all the things to 7... problem?
# JS FUNCTIONS
Function with argument
function myFunk (thing) {
console.log(`Hello ${thing}`)
}
myFunk("World"); // > Hello World
myFunk(7); // > Hello 7
# JS FUNCTIONS
Anonymous function
function () {
return `Hello World`
} // ...
// Callback function
console.log(function () {
return `Hello World`
}); // Hello World
# JS FUNCTIONS
Arrow syntax
const myFunk = (thing) => {
return `Hello ${thing}`
}
console.log(myFunk("Bananas")); // Hello Bananas
# JS FUNCTIONS
Arrow syntax: short version
const myFunk = thing => `Hello ${thing}`;
console.log(myFunk("Bananas"));
// Hello Bananas
# JS FUNCTIONS
Scope considerations: global scope
let globalVariable;
const myFunk = () => {
globalVariable = 1 + 1;
}
console.log("before:", globalVariable); // before: undefined
myFunk();
console.log("after:", globalVariable); // after: 2
# JS FUNCTIONS
Scope considerations: local scope
const myFunk = () => {
let functionScoped = "bananas";
}
console.log(functionScoped); // error: undefined
myFunk();
console.log(functionScoped) // error: undefined
# JS FUNCTIONS
Scope considerations: local scope
const myFunk = () => {
let functionScoped = "bananas";
console.log(functionScoped);
}
myFunk(); // bananas
console.log(functionScoped) // error: undefined
# JS FUNCTIONS
Callback function
const myFunk = () => {
// do something on click
}
btn.addEventListener("click", myFunk);
# JS FUNCTIONS
Callback function
btn.addEventListener("click", () => {
// do something on click
}
);
# JS FUNCTIONS
JS functions
By Elise Allen
JS functions
- 150