Signup/Sign In

JavaScript Functions

JavaScript Functions, just like in any other language, is a set of statements that are used to perform a specific task, like adding two numbers, finding the square of a number, or any user-defined task.

Let's take an example to understand the concept of Functions. If you are building an application for Student Management in which you take data from a student during the registration process and then that data is used at the time of identity card printing, mark sheet printing, any notice printing or anywhere else, then one approach would be that wherever you want student data you can use the student id, query the database and find all the information about the student. You will have to write the same code wherever you want student information. But this will lead to code repetition and if you have to change something in this logic of fetching student data, you will have to make the changes everywhere.

JavaScript Function concept

The better approach to this problem would be defining a function, which takes student id as input, queries the database and returns the student data as output, and then use this function anywhere we want by just calling it. Now, if you have to change something in the logic, you can do it easily.

JavaScript Function: Definition

Now that you have an idea, what a function is, let's see its definition, and how we can define a function, the basic function structure, and using a function in JavaScript.

JavaScript function is a set of statements that are used to perform a specific task. It can take one or more input and can return output as well. Both, taking input and returning an output are optional.

Using functions avoids repetition of the code as we need to write the code only once and then the code can be called anywhere using function name. A function can be helpful in the following scenarios.

  • For instance, suppose you want to add some numbers and display the results on a web page. In that case, you can define the code for adding the numbers in a function and call the function whenever needed.

  • For repetitive tasks like displaying a message whenever a web page is loaded into the browser, we can use functions.

Following image shows the structure of a JavaScript function:

JavaScript function structure

As already mentioned, functions can be parameterized and non-parameterized which means they may or may not take any input. A function that does not take any parameters/inputs is known as non-parametrized function.

A function that takes parameters/inputs which must be defined within parenthesis with the function name(before function definition), is known as a parameterized function. When we call a function, we can provide custom values for these parameters which are then used in function defintion.

To return output from a function, we use the return statement.

Broadly, we can categorize functions into two category:

  1. User defined Function

  2. Built-in Function

This tutorial will mostly focus on the user defined functions because built-in functions are JavaScript library functions which we can call anytime in our script to use them.

JavaScript User-defined Function

JavaScript allows us to define our own functions as per our requirement, as we discussed above. Let's understand how to create our own functions and call them in our script to use them.

Creating a User-defined Function:

In JavaScript, function is defined by using the function keyword followed by the function name and parentheses ( ), to hold params(inputs) if any. A function can have zero or more parameters separated by commas.

The function body is enclosed within curly braces just after the function declaration part(function name and params), and at the end of the function body, we can have a return statment to return some output, if we want.

Following is the syntax for JavaScript user-defined functions:

function function_name(parameter-1, parameter-2,...parameter-n)
{
    // function body
}

where, function_name represents the name of the function and parameter-1, ... , parameter-n represents list of parameters.

Calling a User-defined Function:

After creating a function, we can call it anywhere in our script. The syntax for calling a function is given below:

function_name(val-1, val-2, ..., val-n);

Here, list of parameters represents the values passed to the funtion during function call, which the function has specified in function definition. If a function does not take any parameters then we don't have to provide any value while calling the function.

User-defined Function return Statement:

A function may or may not have a return statement, because not all functions return an output. A return statement is used to specify the value/result/output that is returned from a function.

It's completely optional to have a return statement in your function definition. The execution of a return statement is the final act of a function, after the execution of the return statement, control of execution passes back to the calling statement, which means the control of execution exits the function.

Following is the syntax for using the return statement:

return value;

The return keyword returns the value to the calling statement.

JavaScript User-defined Function Example:

Enough with the theory, let's see some examples now.

<html>
    <head>
        <script>
            function mySumFunction(a, b)
            {
                // return the result
                return a+b;
            }

            let x = myFunction(8, 7);
            alert(x);
        </script>
    </head>
</html>

Above we had defined a simple function to find sum of two numbers and return the result. Let's have some more examples to see JavaScript user-defined functions in action.

In the user-defined function below, we have simply added some text to an HTML element using the innerHTML property.

Function with Parameters Example: In the example below we have a simple function for multiply defined which will take two numeric values as input and will multiply them and return the result.

Another Function Example: In the below example, we have a function with name sum() which takes three parameters. While calling a function, when we provide values for the function parameters, we call them arguments.

JavaScript Built-In Functions

Functions that are provided by JavaScript itself as part of the scripting language, are known as built-in functions. JavaScript provides a rich set of the library that has a lot of built-in functions. Some examples of the built-in functions are : alert(), prompt(), parseInt(), eval() etc.

JavaScript Function as Objects

Yes, you read it right. Functions in JavaScript also are treated as objects and can be assigned to variables. Once we assign a variable with a function, we can then use the variable name to call the function.

Let's take an example for this.

let x = function someFunction(y) {
            document.write("Function called with value: " + y);
        }

// we can call the function using the variable now
x(10);


Function called with value: 10

Conclusion:

In this tutorial, we covered the concept of JavaScript functions in details, covering the basics of functions, why we need them, the structure of a function, how to define them, how to call them, along with examples.



About the author:
I like writing content about C/C++, DBMS, Java, Docker, general How-tos, Linux, PHP, Java, Go lang, Cloud, and Web development. I have 10 years of diverse experience in software development. Founder @ Studytonight