Function
Function are first-class citizens in JavaScript which means, they are like objects and can be passed and returned like other objects
Declaring a Simple function
function function_name(parameter){ body of function; }
functions are not executed until we call them.Making a function call
function_name(parameters)
Returning a function
function function_name(){ return function second(){ console.log("hi") } }
let variable=function_name() since we return a function variable is now pointing to second() Hence now we can invoke second as variable()
Passing a function as a parameter
let variable=function second(){ console.log("hi") }
function function_one(variable){ variable();
}
Here function_Second is passed as a parameter to the first function
Closure
We know that we can return functions as they are objects This property comes from mathematics Closure property states that when a set of numbers is closed under any arithmetic operation such as addition, subtraction, multiplication, and division and is performed on any two numbers of the set with the answer being another number from the set itself. This property is applicable for real numbers, whole numbers, integers, and rational numbers
On similar lines closure in functions implies That the inner function has access to all the variables in the outer function even though the outer function has finished execution Example:
function function_inner(){
var name="jeevan" return function(){ console.log(name)}
};
var calling=function_outer() // here we call and execute the outer function calling()//now we invoke the inner function
output: jeevan// even after executing the outer function still we have access to the inner function.
Use Case: We know that when we execute a function all the variables associated with are garbage collected once the function execution is completed. So what if we had to remember the state of a variable and then use it the next time we call it . For this, we use closure since the lexical scope of the outer function is bound to the inner function even after executing the outer function we can still have an access to all the members inside
Arrow functions
A shorter version of function
function function_name(){
console.log("hi");
}
In arrow syntax we can write it as var variable=()=>{ console.log("hi"); }
Anonymous function
A function with no name is called an anonymous function
example var variable= function(){ console.log("hi")}
variable() output: hi
spread operator
It will spread the elements of any iterable to individual elements syntax ...args
rest operator
Exact opposite of rest syntax...rest