Types Of Functions in Javascript

1. Named function:

A Named function is one that we write in code and then use whenever we need it by referencing its name and providing it with some parameters. Named functions come in handy when we need to call a function several times to give various values to it or run it multiple times.

Javascript
function add(a, b) {
    return a + b;
}
console.log(add(5, 4));

Output
9

2. Anonymous function:

We can define a function in JavaScript without giving it a name. This nameless function is referred to as the Anonymous function. A variable must be assigned to an anonymous function.

Javascript
let add = function (a, b) {
    return a + b;
}
console.log(add(5, 4));

Output
9

3. Nested Functions:

A function in JavaScript can contain one or more inner functions. These Nested Functions fall within the purview of the outer function. The inner function has access to the variables and arguments of the outer function. However, variables declared within inner functions cannot be accessed by outer functions.

Javascript
function msg(firstName) {
    function hey() {
        console.log("Hey " + firstName);
    }

    return hey();
}

msg("Ravi");

Output
Hey Ravi

4. Immediately invoked function expression:

The browser executes the invoked function expression as soon as it detects it. Immediately invoked function expression has the advantage of running instantly where it is situated in the code and producing direct output. That is, it is unaffected by code that occurs later in the script and can be beneficial.

Javascript
let msg = (function() {
    return "Welcome to GfG" ;
})();
console.log(msg);

Output
Welcome to GfG


How to write a function in JavaScript ?

JavaScript functions serve as reusable blocks of code that can be called from anywhere within your application. They eliminate the need to repeat the same code, promoting code reusability and modularity. By breaking down a large program into smaller, manageable functions, programmers can enhance code organization and maintainability.

Functions are one of JavaScript’s core building elements. In JavaScript, a function is comparable to a procedure—a series of words that performs a task or calculates a value—but for a process to qualify as a function, it must accept some input and produce an output with a clear link between the input and the result. To utilize a function, it must be defined in some place within the scope from which it will be called.

Similar Reads

Function Definition

A Function Definition or function statement starts with the function keyword and continues with the following....

Types Of Functions in Javascript

1. Named function:...