Function
A Function Declaration (defining a function)
A Function Call (calling/executing a function)
Types of Functions in JavaScript
- Normal(Regular) Function:
In JavaScript, a regular function is a reusable block of code that performs a specific task. It is defined using the function keyword, followed by a name (optional) and a set of parameters enclosed in parentheses.
//Function Declaration
function functionName(a,b){
return a+b;
}
// function call
const res = functionName(a,b);
console.log(res);
- Anonymous Function:
An anonymous function in JavaScript is a function without a specified name. It is typically defined on the fly and assigned to a variable or used directly as an argument in a function call.
const functionName = function(a,b){
//Do something
}
const result = functionName(3, 4);
console.log(result);
- Immediately Invoked Function Expression (IIFE):
An Immediately Invoked Function Expression (IIFE) is a JavaScript design pattern where a function is defined and executed immediately after its creation. This pattern is often used to create a private scope for variables, preventing them from polluting the global scope.
const result = (function(a,b){
return a+b;
})(2,4);
- Arrow Function:
An arrow function in JavaScript is a concise way to write anonymous functions. Arrow functions were introduced in ECMAScript 6 (ES6) and provide a more compact syntax compared to traditional function expressions.
const functionName = (a,b) => {
// do something
}
- Implicit Return:
If the function body consists of a single expression, the return statement is implicit.
const functionName = (a, b) => a + b;
console.log(functionName(3, 4));
NOTE!: Every function in JavaScript returns undefined
unless and until specified.
Please feel free to add more information to the post if you have any.
Top comments (1)
The following case throws an exception error because of how hoisting works in JS:
while the regular function will print
"wawa"
because of how hoisting works:also, different function types handling
this
and scoping in different ways:firstFunc()
will print out the scope of thetest()
function, while, thesecondFunc()
will print out the global scope, as arrow functions inherit thethis
from the surrounding scope, instead of inheriting current scope