Function
Functions
Default Parameters
Why We Need It?
- If not
1 | const bookings = []; |
- If you have
1 | const bookings = []; |
If you want to skip some parameters, you can set it as undefined
1 | createBooking('LH123', undefined, 1000); |
How Passing Arguments Works:Value vs. Reference
Javascript can only pass by value, no passing by reference.
First-Class vs. Higher-ordered Functions
First-Class Functions
- JavaScript treats functions as first-class citizens
- This means that functions are simply values
- Functions are just another “type” of object
So we can:
Store functions in variables or properties
Passing functions as arguments to other functions
Return functions from functions
Call methods on functions
Higher-Ordered Functions
What is it?
- A function that receives another function as an argument ,that returns a new function, or both
- This is only possible because of first-class functions
Why we need it
- a higher level of abstruction
Functions Accepting Callback Functions
1 | // Functions Accepting Callback Functions |
Functions Ruturning functions
1 | const greet = function (greeting) { |
If you use the arrow function
1 | const greet = greeting => name => console.log(`${greeting}, ${name}`); |
Call()
1 | const lufthansa = { |
The first argument is the object that you want the this point to.The rest argument is the rest argument that the original the function need.
apply()
1 | book.apply(eurowings, [234, 'ajdfhha']); |
Difference: The second argument is an array,to accept origin arguments.
Same as
1 | book.call(eurowings,...[234, 'ajdfhha']); |
bind()
It will return a functions in which the this is the argument you passed in.
1 | book.bind(eurowings)(224, 'asjf'); |
Also, you can use it just like the call()method, passing in more arguments.
If you don’t want to set this, just use null.
Partial application
we can preset some arguments
Immediately Invoked Function Expressions(IIFE)
1 | (function () { |
Or
1 | (() => { |
You can not call it tiwice.
Data Encapsulation and Data Privacy
Closuers
A function always has access to the variable enviroment(VE) of the execution context in which it was created,even after that execution context was gone.
Closure has priority over the scope chain.
A closure gives a function access to all the variables of its parent function, even after that parent function has returned.The function keeps a reference to its outer scope, which preserves the scope chain all the time.
Examples:
let f; const g = function () { const a = 1; f = function () { console.log(a * 3); }; }; g(); f();//3setTimeout()