Day 9 : Function Declaration ,Expression ,Constructor , Hoisting , Self-invoking Function
Function
JavaScript functions are defined with the function keyword. You can use a function declaration or a function expression.
Function Declaration:-
function functionName(parameters) {
// code to be executed
}
Declared functions are not executed immediately. They are "saved for later use", and will be executed later, when they are invoked (called upon).
Example:-
function myFunction(a, b) {
return a * b;
}
myFunction(2,5) // 10
Function Expression:-
A JavaScript function can also be defined using an expression. Example:-
const x = function (a, b) {return a * b};
let z = x(4, 3); // 12
● The function above is actually an anonymous function (a function without a name).
● Functions stored in variables do not need function names. They are always invoked (called) using the variable name.
Function Constructor:-
● Functions can also be defined with a built-in JavaScript function constructor called Function().
Example:-
const myFunction = new Function("a", "b", "return a * b"); let x = myFunction(4, 3); // 12
You actually don't have to use the function constructor.
Function Hoisting:-
● Hoisting is JavaScript's default behaviour of moving declarations to the top of the current scope.
● Hoisting applies to variable declarations and to function declarations. Example:-
myFunction(5);
function myFunction(y) {
return y * y;
} // 25
Functions defined using an expression are not hoisted.
Self-invoking Function:-
● Function expressions can be made "self-invoking".
● A self-invoking expression is invoked (started) automatically, without being called.
● Function expressions will execute automatically if the expression is followed by ().
● You cannot self-invoke a function declaration.
● You have to add parentheses around the function to indicate that it is a function expression.
Example:-
(function () {
let x = "Hello! I called myself"; // I will invoke myself })();
// Hello! I called myself
The function above is actually an anonymous self-invoking function (function without name).
Subscribe to my newsletter
Read articles from Jemin Kikani directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by