Function is a block of code designed to perform a particular task, executed when called or invoked
Declarations
-
Function
-
Function Expression
- Not hoisted
-
Arrow Function
- Un-named function, also called as lambda functions
Types
1. Anonymous function
- Functions without a name, often used as arguments or assigned to variables.
2. Named functions
- With a specific name.
3. Immediately invoked functions ( IIFE )
- Immediately executed after defined.
Scope
- Scope of function is the function in which it is declared or the whole program if defined in top level
Hoisting
Function declarations and generator functions are value hoisted. Function expressions are not hoisted. Refer - Hoisting
Closures
- A function that retains access to its outer scope variables. Before ES6, this was the way to emulate private variables.
- Lexical Environment is created when a function is declared, so closures only form when a function is declared inside a function.
Callbacks
- A function which is passed an argument to another function. Now the parent function can call this function after some tasks
Higher-Order Functions
- Function that takes one or more arguments as a function or returns a function.
Default Parameter in a function
Spread operator
- Allows iterable to be expanded in places where 0 or more arguments or elements are expected
Rest Parameter
- The rest parameter is a syntax that allows a function to take indefinite parameters in a array. This was introduced in ES6.
- In ES5,
arguments
variable used to be present, which consists of all the parameters passed, but this was not a true array andforEach
,map
array methods were not present.
Function binding
- Here greet is a method of person, which refers to name in the object context.
- Assigning the greet method to a variable, this makes it loose its context.
bind
returns a function with a context forthis
attached to it.
- An interesting approach - It works as
this
refers to the object which owns the method rather then who or where its defined.
Asynchronous functions
- Async/Await: Simplifies working with asynchronous code by allowing you to write asynchronous functions using the
async
andawait
keywords.
Generator Functions
- The function defined as
function*
syntax - Generator functions are special type of functions that makes easy to implement the iterators. When a generator function is called, it returns a generator which can be called only once and it will execute the code till the
yield
keyword in the function and return the yield value.
- The
for...of
loop exhaust the yields and does not capture the return statement. The return statement is executed or returned after all the yields are exhausted. Below is the example of how to capture the return.
Functions properties and methods
name
returns the name of the functionslength
returns the length of the arguments expected in the functioncall
andapply
methods call the function by providing the values forthis