JavaScript Functions – Concept to Ease your Web Development Journey

Free Web development courses with real-time projects Start Now!!

Functions are one of the major pillars of JavaScript. Basically, a JavaScript function is a set of statements that performs some tasks or do some computation and then returns the result to the userToday in this JavaScript tutorial we will cover the fundamentals of JavaScript Functions.

We will understand what functions are, how to define and use them, and various other terminologies associated with them. Also, we will take a brief look at the function scope and learn a bit about JavaScript’s built-in functions available to the programmers.

Before starting we would recommend you to take a quick revision on JavaScript Loop Control

JavaScript Functions (1)

What are JavaScript Functions?

A JavaScript function is a procedure or a subprogram, i.e., a block of code that performs a certain task. It is a group of reusable code that you can use anywhere in the code. It helps you to divide a large program into small and manageable functions. With the help of functions, you don’t need to write the same block of code repeatedly. This makes a program a lot more efficient and reduces the code length.

We used some functions like prompt() and write() in our previous JavaScript Tutorials of this series. These are the built-in functions that JavaScript provides, and you will learn more about them later in this tutorial. For now, let’s move onto the syntax of a JavaScript function.

Function Definition

A function definition (also called a function statement or a function declaration) includes a function keyword, with its syntax as follows:

function functionName(parameters)
{
  //statements
}

It is important to separate the parameters with commas.

Return Statement

This is an optional JavaScript statement that returns a value from the function. Unless specified otherwise, a function returns undefined. We use the keyword return, followed by the statement or expression we want to return. This statement should be the last one in the block because it skips all code in the block written after that. We will make use of this statement in the section of Calling Function.

The basic syntax of a return statement is as follows:

return value;

Function Expressions

The function declaration above is syntactically a statement. We can also create a function using a function expression. These functions can be anonymous, i.e., they don’t have any name. This is one of the features we learned about in our article on Introduction to JavaScript. The syntax for these expressions is as follows:

variable = function (parameters){ //expression };

Calling Functions

A defined function doesn’t execute automatically. A function definition only specifies what to do when we execute the function. The actual execution is possible with the help of function invocation or function call. Functions must be in their scope when called and when we are using function expressions in our code. This is because function declarations support hoisting, but function expressions don’t.

The syntax for function invocation is like this:

functionName(arguments);

Like parameters, we separate arguments of a function call with the use of commas.

We are now going to wrap up all we’ve learned so far in two JavaScript programs, one with function declaration and the other with function expression.

Using function declaration:

Code:

<html>
  <body>

    <script>
      function saySomething(){ //function definition
        alert("Hello DataFlair!"); //create an alert in browser
      }
      document.write("Return Type: " + saySomething()); //calling function and returning type
    </script>

  </body>
</html>

Screenshot –

calling function in JS

Output-

JS calling function op

Using function expression:

Code:

<html>
  <body>

    <script>
      var area = function(height, weight){ //function expression
        return height * weight; //returning area of rectangle
      }
      document.write("DataFlair: Using functions</br>");

      document.write("Area of the rectangle is " + area(4, 9)); //calling function by passing parameters
    </script>

  </body>
</html>

Screenshot-

using js function expression

Output –

using JavaScript function expression op

Function Parameters and Arguments

When you begin programming, you often hear the terms: arguments and parameters. Many programmers get confused with these terms, but it is crucial that you understand what they are and how are they different from each other.

Parameters are used inside the parenthesis in a function declaration. It takes whatever value the function arguments contain and work with them for the entirety of the function. The lifetime of parameters is only inside the function. You cannot access or modify them from outside the function. In a function definition, we can pass up to 255 parameters, separated by commas.

On the other hand, arguments are the actual values that we pass to a function at the time of function call. The names of an argument or parameter can be the same or different, as per your convenience. But you need to make sure that the numbers of arguments and parameters for a function are the same.

In the above program, height and weight are parameters, while 4 and 9 are the arguments. height and weight take on the value of 4 and 9 respectively in this case.

Function Scope

A variable defined inside a function cannot be accessed outside it. But a function can access any variable defined as a global variable. When you define a function inside another function, we call that a nested function. This function is the child function of whichever function it is defined in (the parent function). A child function has access to all the variables defined in the parent function or which the parent has access to; vice-versa is not true.

Didn’t you check DataFlair’s latest tutorial on JavaScript Variables?

Too much theory? Get ready to understand exactly what I mean with the following code:

<html>
  <body>
    <h3>DataFlair: Function Scope</h3>

    <script>
      var num1 = 2;
      document.write("Value of number 1 is " + num1 + ". (Global scope)</br>");
      function parentFunction(){ //global function
        var num2 = 4;
        num1 = 8;
        document.write("Value of number 1 is " + num1 + ". (Inside global function)</br>");
        document.write("Value of number 2 is " + num2 + ". (Inside parent function)</br>");
        childFunction(); //child function called
        document.write("Value of number 3 is " + num3 + ". (Inside parent function)</br>");

        function childFunction(){ //nested function
          var num3 = 0;
          document.write("Value of number 2 is " + num2 + ". (Inside child function)</br>");
          document.write("Value of number 3 is " + num3 + ". (Local scope)</br>");
        }
      }
      parentFunction(); //parent function called
    </script>

  </body>
</html>

Screenshot –

function scope in JS

Output-

function scope1 op

Now try the same code again; this time remove the comment from the write function above.

Code:

<html>
  <body>
    <h3>DataFlair: Function Scope</h3>

    <script>
      var num1 = 2;
      document.write("Value of number 1 is " + num1 + ". (Global scope)</br>");
      function parentFunction(){ //global function
        var num2 = 4;
        num1 = 8;
        document.write("Value of number 1 is " + num1 + ". (Inside global function)</br>");
        document.write("Value of number 2 is " + num2 + ". (Inside parent function)</br>");
        childFunction(); //child function called
        //document.write("Value of number 3 is " + num3 + ". (Inside parent function)</br>");

        function childFunction(){ //nested function
          var num3 = 0;
          document.write("Value of number 2 is " + num2 + ". (Inside child function)</br>");
          document.write("Value of number 3 is " + num3 + ". (Local scope)</br>");
        }
      }
      parentFunction(); //parent function called
    </script>

  </body>
</html>

Screenshot –

function scope2

Output-

function scope2 op

Note that in both cases, the browser displays the same output. The difference is that when you run your code the second time, you get an error. You wanted to print the value of num3 at last, but that line is missing. This is because parentFunction tried to access a local variable of its child i.e. childFunction.

Types of JavaScript Functions

1. Recursive Functions

It is possible for a function to call itself directly or indirectly. A function that calls itself during its execution is a recursive function. This allows a function to repeat for multiple iterations, minimizing the code. The problem with these functions is that, if not written properly, they can cause infinite loops and other unexpected results.

Recursive Function in JavaScript

Let’s understand these functions a little better with the help of a JavaScript code to find the factorial of a number. The flowchart below depicts the algorithm for calculating the factorial of a number.

Do you know how to construct loops in JavaScript?

Code:

<html>
<body>
  <h3>DataFlair: Recursive function</h3>

    <script>
      let fact = 1, num = 5; //initializing variables
      function calculateFactorial(number){ //function definition
        if(number == 0)
          return 1; // 0! = 1
        else
          return number * calculateFactorial(number - 1); //recursion: calling itself
      }
      document.write("The factorial of " + num + " is " + calculateFactorial(num)); //function called with an argument
    </script>

  </body>
</html>

Screenshot –

JS recursive function

Output –

JavaScript recursive function op

2. Arrow Functions

An arrow function, introduced with ECMAScript 2015, is a compact way to write JavaScript functions. They have shorter syntax than function expressions and doesn’t work with this keyword. These functions are always anonymous i.e., they have no names. This is why we don’t use them as methods, and the reason we cannot use them as constructors.

These functions use the => arrow to declare a function rather than the function keyword.
Let’s see with an example of how these functions reduce the code length by comparing it with a normal function.

Code:

<html>
  <body>

    <script>
      function hello(str){ //function declaration
        return "Hello " + str;
      }
      document.write("By a regular function:</br>");
      document.write(hello("DataFlair</br></br>")); //function call

      var helloAgain = str => "Hello " + str; //arrow function

      document.write("By an arrow function:</br>");
      document.write(helloAgain("DataFlair")); //function call
    </script>

  </body>
</html>

Screenshot –

JavaScript arrow Function

Output-

JavaScript arrow functionop

These functions are usually helpful in large-scale projects. Using these functions in the program helps programmers to optimize their code. Practice these functions as much as you can to gain mastery over them.

All the functions we discussed above were the ones you defined. What if we don’t want to do that? Is there a way to use predefined codes to save you time and money? The answer to that question is yes, with the help of JavaScript built-in methods. Methods are nothing, but functions associated with a JavaScript object.

3. Built-in Methods

JavaScript provides various built-in methods for programmers to use directly. The JavaScript interpreter understands these methods without you having to define them. You can call these methods anywhere in your program directly. It is not possible to know all the built-in methods in a single tutorial. You will learn their use as you code more in JavaScript. Some of the most common built-in functions of JavaScript are as follows:

  • alert()

This method displays text in a dialog box that pops up on the screen. These are generally used to convey some information or a warning to the user before loading the page on the browser.

  • prompt()

Like alert(), the prompt() method also displays text in a dialog box on the screen. But this method provides the user with the facility to enter some data as well.

  • write()

This JavaScript method is very useful when you want to print something on your desktop using JavaScript only. It helps programmers in dynamic programming since it prints the content on the browser only when an event occurs.

  • getElementById()

This method returns the element whose ID you passed in the function as an argument. If the ID passed to the function doesn’t exist, it returns null.

  • getElementsByClassName()

This JavaScript method returns a collection of all the elements in the document that have the same class name as the argument. This collection is the collection of nodes, returned as a JavaScript NodeList. You can access each node by its index number (starting with 0). These are explained in further detail in DataFlair’s JavaScript Tutorial on Document Object Model.

  • getDate()

This JavaScript method provides special functionality to our program. It returns the current date returned by the device. This method is always used with a Date object. You will learn more about this object and other methods associated with it in our tutorial on JavaScript Date and Time.

  • includes()

This method checks a collection for a specific string that we want to find. Based on whether or not the string is a part of that collection, it returns true or false. Remember, this method is case sensitive; you need to be careful about what you pass as an argument.

Summary

With this, we come to the end of our tutorial on JavaScript Functions. With the help of function keyword, we can define JavaScript function. A function can include one or more parameters. It is optional to specify functions parameter values while executing it. In this article, we covered various topics related to JavaScript functions. I want you to practice these codes, as much as you can. You will be an expert on JavaScript functions as you continue programming in JavaScript.

Now, you must go through our next article on JavaScript Class

If there is something which we missed, please let us know through comments. Waiting for your valuable feedback.

Happy Learning!

If you are Happy with DataFlair, do not forget to make us happy with your positive feedback on Google

follow dataflair on YouTube

1 Response

  1. Yash Marmat says:

    Explanation of topic is good but also provide good explanation for the code as well (not just ouput)

Leave a Reply

Your email address will not be published. Required fields are marked *