View video tutorial

JAVASCRIPT Functions

JAVASCRIPT

JavaScript function is a self contained standalone block of code.

JavaScript Functions


➔ JavaScript function is reusable block of code that performs specific kinds of work.

➔ Functions are the building blocks of any programming language, including the JavaScript programming language.

➔ Programmers organize and manage a larger task by dividing it into smaller modules, and implementing the divided tasks into functions.

Function definition syntax


➔ The most common and easiest way to define a function is to use the function keyword, followed by the function name, parentheses, and the function body.

➔ Optional parameters can be enclosed between two parentheses.

➔ Function implementation is done in the function body, that is, within the curly braces.

Function syntax

<script>
    // Function Declaration
    function demo(name) { // 'name' is a parameter
        return "Hello, " + name + "!";
    }

    // Invoke the function 
    let msg = demo("David"); // "David" is an argument replaces parameter 'name'
    console.log(msg); // Output: Hello, David!
</script>
JavaScript Function call on page load

Example

<!DOCTYPE html>
<html>
<head>
    <title>JavaScript function call during page load example</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta charset="utf-8">
</head>
<body>
    <h3>JavaScript function call during page load example</h3>
    <p>Full Name is: <span id="demo"></span></p>
    <script>
        // Function Declaration
        function myfunc(name) { // 'name' is a parameter
            return "Hello, " + name + "!";
        }
        // Invoke the function 
        let msg = myfunc("David"); // "David" is an argument replaces parameter 'name'
        document.getElementById("demo").textContent = msg;
    </script>
</body>
</html>
Try it Now »

Copy the code and click on the "Try it Now" button to see how it works.


JavaScript Function call after page load

Example

<!DOCTYPE html>
<html>
<head>
    <title>JavaScript function call after page load example</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta charset="utf-8">
</head>
<body>
    <h3>JavaScript function call after page load example</h3>
    <div><input type="text" value="David" id="tf1"><button onclick='greeting();'>Click</button></div>
    <p>Full Name is: <span id="demo"></span></p>
    <script>
        // Function Declaration
        function myfunc(name) { // 'name' is a parameter
            return "Hello, " + name + "!";
        }
        function greeting() {
            let x = document.getElementById("tf1").value
            let msg = myfunc(x); // store the return value to a varible msg. 
            document.getElementById("demo").textContent = msg;
        }
    </script>
</body>
</html>
Try it Now »

Copy the code and click on the "Try it Now" button to see how it works.


Types of JavaScript Function


➔ JavaScript Standard function.

➔ JavaScript function expression.

➔ JavaScript Arrow Function.

➔ JavaScript Callback Function.

➔ JavaScript Immediately Invoked Function Expression.

➔ JavaScript method functions as object members.

JavaScript Function expression

➔ A function is created and assigned to a variable, this variable will act as a function.

➔ There is no name associated with the function definition.

➔ That's why it's also called an anonymous function.

Example

<!DOCTYPE html>
<html>
<head>
    <title>JavaScript anonymous function example</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta charset="utf-8">
    <style>
        input {
            padding: 10px;
            margin: 5px;
        }
    </style>
</head>
<body>
    <h3>JavaScript anonymous function example</h3>
    <div>
        <input type="number" value="10" id="tf1" /><br>
        <input type="number" value="20" id="tf2" /><br>
        <input type='button' onclick='calc();' value="Add" />
    </div>
    <p>Result is: <span id="demo"></span></p>
    <script>
        // Anonymous Function Declaration
        const addition = function (a, b) { return a + b; };
        //Standard function
        function calc() {
            let x = parseInt(document.getElementById("tf1").value);
            let y = parseInt(document.getElementById("tf2").value);
            let msg = addition(x, y);  // call function expression
            document.getElementById("demo").textContent = msg;
        }
    </script>
</body>
</html>
Try it Now »

Copy the code and click on the "Try it Now" button to see how it works.


JavaScript Arrow Function

➔ Arrow function uses very concise syntax over function expression.

➔ This syntax uses a arrow like symbol.

➔ That's why it's also called arrow function.

Example

<!DOCTYPE html>
<html>
<head>
    <title>JavaScript arrow function example</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta charset="utf-8">
    <style>
        input {
            padding: 10px 20px;
            margin: 5px;
        }
    </style>
</head>
<body>
    <h3>JavaScript arrow function example</h3>
    <div><input type="number" value="10" id="tf1" /><br>
        <input type="number" value="20" id="tf2" /><br>
        <input type='button' onclick='calc();' value="Add" />
    </div>
    <p>Result is: <span id="demo"></span></p>
    <script>
        // Arrow Function Declaration
        const addition = (a, b) => a + b;
        //Standard function
        function calc() {
            let x = parseInt(document.getElementById("tf1").value);
            let y = parseInt(document.getElementById("tf2").value);
            let msg = addition(x, y);  // call arrow function
            document.getElementById("demo").textContent = msg;
        }
    </script>
</body>
</html>
Try it Now »

Copy the code and click on the "Try it Now" button to see how it works.


JavaScript Callback Function

➔ Callback function is used to pass to other function as an argument.

➔ Any function can accept function as argument.

➔ Callback function is very useful in event driven programming.

Callback function EventListener Example1

<!DOCTYPE html>
<html>
<head>
    <title>JavaScript Callback Function Example</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta charset="utf-8">
    <style>
        input {
            padding: 10px 20px;
            margin: 5px;
        }
    </style>
</head>
<body>
    <h3>JavaScript Callback Functions Example</h3>
    <div><input type="number" value="10" id="tf1" /><br>
        <input type="number" value="20" id="tf2" /><br>
        <input type='button' id='btn' value="Add" />
    </div>
    <p>Result is: <span id="demo"></span></p>
    <script>
        let button = document.getElementById("btn");
        // Callback Function is passed to other function.
        button.addEventListener('click', calc); //function is passed as an argument
        //Arrow Function Declaration
        const addition = (a, b) => a + b;
        //Standard function
        function calc() {
            let x = parseInt(document.getElementById("tf1").value);
            let y = parseInt(document.getElementById("tf2").value);
            let msg = addition(x, y);  // call arrow function
            document.getElementById("demo").textContent = msg;
        }
    </script>
</body>
</html>
Try it Now »

Copy the code and click on the "Try it Now" button to see how it works.


Callback function Example2

<!DOCTYPE html>
<html>
<head>
    <title>JavaScript Callback Function Example</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta charset="utf-8">
    <style>
        input {
            padding: 10px 20px;
            margin: 5px;
        }
    </style>
</head>
<body>
    <h3>JavaScript Callback Functions Example</h3>
    <div><input type="number" value="10" id="tf1" /><br>
        <input type="number" value="20" id="tf2" /><br>
        <input type='button' id='btn' value="Add" onclick="myfunc()" />
    </div>
    <p>Result is: <span id="demo"></span></p>
    <script>
        //function uses callback function as an argument.
        function calc(a, b, callback) {
            return callback(a, b);
        }
        //Callback Function Declaration
        function addition(x, y) {
            return x + y;
        }
        //Callback Function Declaration
        function multiplication(x, y) {
            return x * y;
        }
        //Standard function
        function myfunc() {
            let x = parseInt(document.getElementById("tf1").value);
            let y = parseInt(document.getElementById("tf2").value);
            let sum = calc(x, y, addition);
            let mul = calc(x, y, multiplication);
            document.getElementById("demo").textContent = "Sum is: " + sum + " and " + "Mul is: " + mul;
        }
    </script>
</body>
</html>
Try it Now »

Copy the code and click on the "Try it Now" button to see how it works.


JavaScript Immediately Invoked Function Expression (IIFE)

➔ Function runs immediately.

IIFE Function syntax

    <script>
        /*parentheses outside the expression syntax*/
        (function () {
            // Code to run immediately
            console.log("This is IIFE function ");
        })();
        /*parentheses inside the expression syntax*/
        (function () {
            // Code to run immediately
            console.log("This is IIFE function");
        }());
         /*arrow function syntax*/
        (() => {
            // Code to run immediately
            console.log("This is IIFE function");
        })();
        /*passing argument*/
        (function (message) {
            console.log(message); /* output is: hello world */
        })("Hello world");
    </script>

Example IIFE

<!DOCTYPE html>
<html>
<head>
    <title>JavaScript IIFE function example</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta charset="utf-8">
</head>
<body>
    <h3>JavaScript IIFE function example</h3>
    <script>
        (function (message) {
            console.log(message); /* output is: hello world */
        })("Hello world");
    </script>
</body>
</html>
Try it Now »

Copy the code and click on the "Try it Now" button to see how it works.


Function vs Method in JavaScript


Function Method
Function is a block of code. Mehtod is a block of code in object or class.
Function is self contained standalone code block. Method is a class contained code block.
Independent and can be invoked by the function name. ex: functionName(); Dependent on object name and preceded by object name when invoke a method. ex: object.methodName();
Syntax of a Function is:
function functionName(parameters) {
  /*function implementation*/
}
Syntax of a Method is:
object = {
  methodName: function() {
   /*function implementation*/
  }
};