JavaScript Functions

JavaScript Functions in Depth

In this article, I am going to discuss JavaScript Functions with Examples. Please read our previous article where we discussed JavaScript Loops in Detail. At the end of this article, you will understand what are JavaScript Functions and when and how to use Functions in JavaScript with examples.

Why we need JavaScript Functions?

When we write a program, we often required to perform the same action in many places. For example, we want to display a message to the users when they complete an action.

To avoid repeating the same code all over places, we can use a function to wrap that code and reuse it. JavaScript provides many built-in functions such as alert() and console.log()

If we have a few lines of code that needs to be used multiple times, we can create a function that contains the repeating lines of code and then call the function wherever we want.

What is function?

A functions is collection of statements that can be run anywhere at any time. Functions allow breaking a large program into smaller pieces. A function is a reusable block of code

  1. Designed to perform a particular task
  2. Can be invoked(call) from other code
  3. Usually has a name
  4. Can take parameters and return a value
Why to use functions?

More manageable code

  1. Split large program into smaller pieces
  2. Better organization of the program
  3. Improve code readability and understandability

Improves code maintainability

  1. Promotes code reuse
  2. Avoids repeating code
JavaScript Function Syntax:
function functionName(param1, param2, ...paramN) {
      //code to be executed
      return anyValue;//return is used if function return any value otherwise not
}
How to Create a Function in JavaScript

In JavaScript, functions can be created inside the JavaScript script tag only. function is a reserved keyword of JavaScript .Use the keyword function with the name of the function

After the function name, open and close parentheses (). After parenthesis, open and close curly braces {}. Within curly braces, write your lines of code from where the function starts and where ends are kept inside in curly braces

Example to understand JavaScript Function:
<html>
<head>
    <title>Functions example!</title>
    <script type="text/javascript">
        function myFunction() {
            document.write("This is a small function.<br />");
        }
        myFunction();
    </script>
</head>
<body>
</body>
</html>
Declaring and Creating Function in JavaScript

Declaring and Creating Function in JavaScript

Typically a function has a name (it is used to call the function and describes its purpose) and a body (it contains the programming code and is surrounded by { and }).

Function in JavaScript doesn’t have a return type.

Ways to Define a Function in JavaScript

Functions can be defined in several ways

1.By function declaration
function printHello() { console.log(‘Hello’) };

2.By function Expression
var printHello = function () { console.log(‘Hello’) };
var printHello = function printFunct() { console.log(‘Hello’) };

3.Using the constructor of the Function object
var printHello = new Function(‘console.log(“Hello”)’);

Note: Constructor is nothing but it is used for initializing the function which we will discuss in a later chapter.

How to call a function?

To call a JavaScript function, simply use

  1. The function’s name
  2. Parenthesis: ()
  3. A semicolon: ;

For example, printHello();

Parenthesis are mandatory to call a function. This will execute the code in the function’s body which will print the following:

Hello

A function can be called from :

  1. Any other function
  2. A function that calls itself, is called a recursive function. When a function calls itself it gets repeated again and again until the defined condition meets. Recursive functions are such type of functions which calls themselves.
  3. Itself (a process is known as recursion)

Example:

function print() {
     console.log('printed');
}

function anotherPrint() {
      print();
      anotherPrint(); // recursion
}
Function Parameters:

A function accepts zero, one, or multiple parameters. If there are multiple parameters, we need to separate them by commas (,). The following declares a function named show() that accepts no parameter:

function show() {
     //...
}

The following declares a function named square() that accepts one parameter:

function square(x) {
    //...
}

And the following declares a function named add() that accepts two parameters:

function add(a,b) {
    //...
}

To pass information to a function, we can use parameters

  1. Parameters accept input data in the function
  2. Each parameter has a name
  3. We can pass zero or several input values
  4. Parameters are assigned to particular values (called “arguments“) when the function is called

Parameters can change the function behavior depending on the passed values

Defining and Using Function Parameters

Function’s behavior depends on its parameters. Parameters can be of any type number, string, object, array, etc and even the function.

Example:

function printNumber(number1, number2) {
            var max = number1;
            if (number2 > number1)
                max = number2;
            console.log('Maximal number: ' + max);
        }
Calling Functions with Parameters in JavaScript:

To call a function and pass values to its parameters:

  1. Use the function’s name
  2. Followed by a list of expressions for each parameter

Examples:

printNumber(-5, -10);
printNumber(a + b, c);
printNumber(2 + 3, 10);
printNumber(100, 200);
JavaScript function with Arguments

We can create functions with arguments as well. Arguments should be specified within parenthesis (). Every function have a special object called arguments which holds the arguments passed to it. No need to be explicitly declared and exists in every JS function

Syntax:

function functionname(arg1, arg2) {
            //code to be executed
        }
Example1:
function printArguments() {
            for (var i in arguments) {
                console.log(arguments[i]);
            }
}
printArguments(1, 2, 3, 4); // 1, 2, 3, 4
Example2:
<html>
<head>
    <script type="text/javascript">
        var count = 0;
        function countVowels(name) {
            for (var i = 0; i < name.length; i++) {
                if (name[i] == "a" || name[i] == "e" || name[i] == "i" || name[i] == "o" || name[i] == "u")
                    count = count + 1;
            }
            document.write("Hello " + name + "!!! Your name has " + count + " vowels.");
        }
        var myName = prompt("Please enter your name");
        countVowels(myName);
    </script>
</head>
<body>
</body>
</html>
Parameters vs. Arguments

The terms parameters and arguments are often used vice versa. However, they are essentially different. The parameters are used when declaring the function. For example, in the getcube() function, the number is the parameter.

On the other hand, the arguments are nothing but the values the function receives from each parameter at the time the function is called. In the case of the getcube() function, the 4 number is the argument.

Example:

<html>
<body>
    <script>
        function getcube(number) {
            alert(number * number * number);
        }
    </script>
    <form>
        <input type="button" value="click" onclick="getcube(4)" />
    </form>
</body>
</html>
JavaScript Function with Return Value

We can also create JavaScript functions that return values. Inside the function, we need to use the keyword return followed by the value to be returned. Every JavaScript function returns undefined unless otherwise specified.

Example:

<script>
        function show(message) {
            console.log(message);
        }

        let result = show('Hello');
        console.log('Result:', result);
</script>

Output:

Hello

Result: undefined

Syntax:

function functionname(arg1, arg2) {
            //code to be executed
            return val1;
}

Functions can return any type of data E.g. number, string, object, etc. We can use return keyword to return a result

Example:
<html>
<head>
    <script type="text/javascript">
        function createStudent(name, age, gender) {
            var obj = { name: name, age: age, gender: gender };
            return obj;
        }

        var student = createStudent("Shagufta", 21, "Female");
        console.log(student);
    </script>
</head>
<body>
</body>
</html>
The return statement

The return statement returns the specified expression to the caller and stops the execution of the function. For Example, return -1;

To stop the function’s execution, use just: return;

Return can be used several times in a function body. To return a different value in different cases

Function Scope

Every variable has its scope of usage. The scope defines where the variable is accessible

Example:

<html>
<head>
    <script type="text/javascript">
        var arr = [1, 2, 3, 4, 5, 6, 7]; // global scope
        function countOccurences(value) {
            var count = 0; // local scope (for the function only)
            for (var i = 0; i < arr.length; i++)
                if (arr[i] == value) count++;
            return count;
        }
        countOccurences(arr);
        console.log(arr); // [1, 2, 3, 4, 5, 6, 7]
        console.log(typeof (count)); // undefined
    </script>
</head>
<body>
</body>
</html>
Local Scope

Example of local function scope variables:

<html>
<head>
    <script type="text/javascript">
        function play() {
            for (var x = 1; x < 5; x++) {
                var y = x * x;
                console.log(x + " " + y);
            }
        }

        play();
        console.log(typeof (x)); // undefined
        console.log(typeof (y)); // undefined
    </script>
</head>
<body>
</body>
</html>
Global Scope

Example of global scope variables:

<html>
<head>
    <script type="text/javascript">
        for (var x = 1; x < 5; x++) {
            var y = x * x;
            console.log(x + " " + y);
        }

        console.log("x=" + x + " y=" + y); // x=5 y=16
        // Now "x" and "y" are variables in the global scope
    </script>
</head>
<body>
</body>
</html>

Global variables (declared without var) are different than variables in the global scope

Functions in JavaScript can be Nested
  • Functions in JavaScript can hold other functions
  • Function can be placed inside other function
  • Inner functions can access the variables hold in their parent

Example:

function add() {
            var counter = 0;
            function plus() { counter += 1; }
            plus();
            return counter;
}
Function Overloading

Function overloading means multiple functions with the same name. JavaScript does not support function overloading i.e. only one function with a specified name can exist in the same scope

Example:

function printText(number, text) {
            switch (arguments.length) {
                case 1: console.log('Number :' + number); break;
                case 2:
                    console.log('Number :' + number);
                    console.log('Text :' + text);
                    break;
            }
        }
        printText(5); // Logs 5
        printText(5, 'JavaScript Tutorials'); // Logs 5 and JavsScript Tutorials

In the next article, I am going to discuss Function Expressions in JavaScript with examples. Here, in this article, I try to explain JavaScript Functions with examples. I hope this article will helps you with your need. I would like to have your feedback. Please post your feedback, question, or comments about this article.

Leave a Reply

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