Functions JS Flashcards
What is a function declaration vs function expression? What are the differences? (hoisting)
function declaration === function doStuff() {}; function expression === const doStuff = function() {} Or const doStuff = () => { }
Function declarations are hoisted, expressions are not. Hoisting allows functions to be safely used in code before they are declared. e.g. it hoists all declarations to the top of their scope by default, so it doesn’t matter where you declare and use them.
What are anonymous functions, give example.
Functions without a name. Arrow functions are shorthand for declaring anonymous functions.
example: let sayHello = (name) => { console.log(name) } sayHello("Chris")
Explain scope.
- Block scope
- Function scope
- Global scope
Global = Variables declared outside of any function. Local = A variable declared inside a function is only visible inside that function Block = A let or Const declared inside a block e.g. an if Statement
Variables declared with the var keyword can NOT have block scope.
Parameters vs Arguments
Parameters are the items listed between the parentheses in the function declaration. let b = (paramOne, paramTwo) => { }
Function arguments are the actual values we decide to pass to the function
b(argOne, argTwo)
What is a Higher-Order function? Some Examples.
A higher order function is identified by:
- A function that returns a function
- A function that takes in a function as an argument
Examples: forEach() map() filter() reduce()
What is a callback function?
A callback is a function passed into another function as an argument to be executed later.
students.map(callbackfunction(item){})
When do you need to use function declaration over a function expression?
function declarations have access to the "this" keyword function name() { //has access to "this" }
let name = () => { //does NOT have access to "this" }
What is a Set, and name a use case.
Sets are basically arrays but every value has to be unique.
Sets are good for removing duplicate values from an array.
What is a Map, and name a use case.
Maps are objects that remember the insertion order, and can have any value (OBJECTS OR PRIMITIVE VALUES) as keys.
Maps are good if you need to use non string values (e.g. objects) as keys