Functions in JavaScript: Closures in JavaScript:

 

  • Functions in Javascript:

There may be a certain piece of code that you would want to run multiple times in your program. In such cases, instead of writing the same code several times, it is better to wrap that code inside something called a function and then reuse that function as and when needed.

Functions can be defined in Javascript using the following syntax:

function function_name (parameters) {

lines of code 

}

 

We use the function keyword followed by the function name of our own choice. Parameters are certain values which may be required inside a function. These values are passed while calling that function.

Note: Parameters are optional, a functional may or may not have parameters.

 

What does calling the function mean?

Calling a function simply means using that function whenever needed. It is also called invoking a function. 

Examples:

Function with parameters:

Function without parameters:








  • Returning values from a function:

Suppose we make a function to add two numbers. What do you think can be done with the result of addition? First, we can directly do something like display the result inside the function itself. Another common requirement is to get the result outside the function, where it is called so that it can be used in the desired way.

For this purpose, ‘return’ keyword is used. It has two purposes:

    1. return keyword is used to return any value to the function caller.
    2. return keyword immediately stops the execution of the function and lines after it inside the function are not executed.

Example:

The result inside the function is returned using the return keyword. The value gets returned to where the function is called.

It can be observed above that lines after the return statement are not executed since return immediately stops the execution of the function.


  • Closures in Javascript:

Before discussing closures, one must be aware of the concept of nested functions and returning a function.

 

Nested function:

A function inside a function is called a nested function.

Example:

Returning a function:

Javascript also allows us to return a function inside another function.

Confusing, right? Here is an example:

Now, let us understand the concept of Closures.

When there is a nested function, Javascript allows the nested function to access the outer scope of the outside function even when the outer function is closed.

Example:

In the above code, we can observe that the inner function (operate) is able to access variables ‘a’ and ‘b’ defined in the outer scope inside the outer function.

Comments

Popular posts from this blog

Day 9: CSS - Font Formate

else-if condition in if-else statements: Concatenation in JavaScript :

Day 27: Css Variable