Function in JavaScript

Functions are the basic building blocks in the JavaScript.
In simple words, A function is a group of statements which can be run when you need them to run. It is like a procedure.

Define a function

The function defination (or function declaration) consists of 4 parts.


function funName([parameters]){
    //function body
}
                    
  • function keyword: to declare a function, function keyword is used before the name of the function
  • function name: in above syntax, function name is funName, by which you can call the function. function name is optional, but most of the times, you will be prodividing function name.
  • parameters: When you need to pass some data to function, you will use the parameter. This field is optional.
  • function body: function body is what you will write between {}. Function body is executed when a function is called. The function can also be without a function body.
    return: sometimes, you need to return the result or some value from the function, then return statement is used. The function body is executed till the return statement is encountered. If there is some code after the return statement, it is not exectued. Please note that It is not necessary to use a return statement in every function. Whenever you need to return some value, then you can use the return function. When there is no return statment, function returns undefined.

Let us create a function which adds two variables and returns the result.


function addition(operand1, operand2){
    return operand1 + operand2;
}
                    

function name is addtion. It adds two parameters passed to the function and returns the result. The result is returned where the function is called.
We will see, how to call a function.


function printValue(val){
    console.log(`This ${val} is printed inside function`);
}
                    

As you can see from above code, function printValue takes parameter val and prints it.
It doesn't contain any return statement. So it returns undefined.


function printVal(val){
    if(true){ // Any condition can be here
        console.log(`This ${val} is printed inside function`);
        return;
    }
    console.log("Will this be printed?");
}
                    

Above example is more practical one. You can have if inside function and if condition is true, other code should not be executed, then you can use return.
In this example, we haven't return any value but if you want to return anything you can use return [value], where [value] is any value or variable.

Calling a functions

Defining function doesn't do any action. You need to call a function to execute the function.
To call a function, all you need to write is functionName([arguments]). Let us have a look at some examples.


let result = addition(4, 3);
console.log(result);
//output: 7

console.log(addition(8,9));
//output: 17
                    

We have called the addition function created above. It is called with two arguments since addition has two parameters. It returns the result which is saved to result variable.
You can directly call the function inside a function like console.log, which will print the result returned by the function.


let returnVal = demoFun();
console.log(returnVal);
//outupt: "This is demo function";
//        undefined

function demoFun(){
    console.log("This is demo function");
}
                    

As we have discussed, if function is not returning anything, or only have return statement without any value, it will return undefined.
In above function demoFun is not taking any arguments. So it is called by demoFun(). So when it is called, it will execute the function body and returns undefined. That is logged. So you can see why output is like that.

There are other ways to call a function. But most of the times, you will be using the above method. We will see them in coming chapters.

Default Parameters

We already have seen how to use parameters while defining a function. The issue will occur when you forgot to pass arguments while calling a function. Let us understand it with an example.


let result = addition(4);
console.log(result);
//output: NaN
                    

You see the error? addition asks for 2 arguments while we passed only 1 argument. So it returns NaN.
To make sure that, it doesn't happen, default arguments should be used.
Default parameters were introduced in ECMAScript 6. Before that, you need to add a condition to check for the parameter.


function addition(operand1, operand2 = 4){
    return operand1 + operand2;
}

let result = addition(5,6);
console.log(result);
//output: 11

let result1 = addition(5);
console.log(result1);
//output: 9

function addition2(operand1, operand2 = 7, operand3 = 9){
    return operand1 + operand2 + operand3;
}

console.log(addition2(1, 2));
//output: 12
                    

As you can see, operand2's default value of 4. So if the second argument is not passed while calling the function, it will take a default value. And if the second parameter is passed, then passed value is used.
Same thing works with function addition2.

Extra Arguments

What happens when a function has 2 parameters but you pass 3?
JavaScript doesn't show any error just like when a function has 2 params but you pass the only single argument.
JavaScript ignores the other extra parameters.


function add(operand1, operand2){
    return operand1 + operand2;
}

let result = add(2,3,4);
console.log(result);
//output: 5
                    

As you can see, when you pass 3 arguments while calling add function, it will use only the first two and ignores the third one.
There are concepts like spread parameters and rest parameters but we will see them after learning about array.

Self Calling Functions

There will be a need when you need a function calls itself. That is called a self-calling function. Most of the times, self calling function will not have any name. So you can just call it once. When you need some function called only once, then the self-calling function will be a great help.
Syntax is something like this : (function declaration)()
You need to wrap the function declaration inside () and at last add ()


let data = (function(){
    console.log("This is data");
})();
//output: This is data
                    

The above function will call itself. and will execute the function body.

Conclusion

In this section, you learn about declaring a function and calling a function.
A function is a basic building block and it is one of the most used fundas in JavaScript programming. You need to practice it a lot.
In next section, you will learn about function expression in JavaScript.