Functions in JavaScript

A block of certain statements used to perform any task is called function. It encapsulates a set of instructions that can be executed multiple times with different inputs, providing a way to structure and organize code in a logical and reusable manner.

Different types of functions:

  • Named Function: A function declared with any name using function keyword.

      function add(a, b) {
          console.log(a+b);
      }
      //Example: add(1,2);  will print 3 in result.
    
  • Anonymous Function: A function declared without name but stored in any variable for call.

      let add = function(a, b) {
          return a + b;
      };
      console.log(add(2,4));
      //console.log(add(2,4)); will print 6 in result.
    
  • Arrow Function: A concise way of writing function in JavaScript introduced in the ES6 version.

      let add = (a, b) => a + b;
      console.log(add(6,14));
      //console.log(add(6,14)); will print 20 in result.
    

    We'll use the arrow function more in DOM manipulation.

  • Constructor Function: A function used to create a new object with shared prototype is called Constructor function. It's used with two different keywords: new and this .

function Person(name, age) {
    this.name = name;
    this.age = age;
}
let person1 = new Person("Ritik", 19);
let person2 = new Person("Raushan", 19);
console.log(person1);
console.log(person2);

  • Recursive Function: A function which call itself is called recursive function. Here a certain term is defined for which it itself is called to perform task.
function factorial(n) {
    if (n === 0) {
        return 1;
    }
    return n * factorial(n - 1);
}
console.log(factorial(5));
//console.log(factorial(5)); will print 120 in result.
  • Higher-Order Function: A function which takes multiple arguments including function or returns a function as result is called Higher- Order Function.

setTimeout : It calls a function after few seconds as per user choice. It's executed only once throughout the execution. Here arrow function is also used.

syntax: setTimeout(functionName, timeinMillisecond);

console.log("Before Hii");
setTimeout( ()=>{
    console.log("Hii");
}, 2000);
console.log("After Hii");

While execution, we know JS is single threaded so at one look it seems that line 1 will be printed then line 3 and lastly line 5 but due to setTimeout line 3 is getting delayed by 2millisecond.

While execution, we know JS is single threaded so at one look it seems that line 1 will be printed then line 3 and lastly line 5 but due to setTimeout line 3 is getting delayed by 2millisecond.

setInterval : It repeatedly calls a function after an interval of time until clearInterval() is called, or the window is closed.

syntax: setInterval(functionName, timeinMillisecond);

console.log("Before Hii");
setInterval( ()=>{
    console.log("Keep saying Hii");
}, 1000);
console.log("After Hii");
/*Output: Before Hii
          After Hii
          Keep saying Hii
          Keep saying Hii
          Keep saying Hii
          Keep saying Hii
           .........
untill clearInterval() is called

clearInterval() :It clears the timer set to the setInterval method. We need to store the setInterval in any variable to pass in this clearInterval().

Callback: A function that is passed as an argument to another function and is called after the main function has completely executed is Callback.

function main(person,callback){
    console.log(person+" is learning functions.");
    callback();
 }
   function callback(){
    console.log("It's callback function.");
    }
main("Ritik",callback);

/*Output: Ritik is learning functions.
          It's callback function.

In the above code main function is taking two arguments one variable and other function callback ,which is called in the main function and executed once main function is finished.

Use of arrow function and High Order Function in DOM:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        body{
            margin-top: 20vh;
            text-align: center;
            justify-content: center;
        }
    </style>
</head>
<body>
    <button id="student1">Ritik</button>
    <button id="student2">Raushan</button>
    <button id="student3">Sachin</button>
</body>
<script>
    let a=document.querySelector("#student1");
    let b=document.querySelector("#student2");
    let c=document.querySelector("#student3");

    function getName(button){
        alert(`Hii I'm  ${button.textContent}`);
        button.style.backgroundColor="Green";
    }

    a.addEventListener("click", ()=>{
        getName(a);
    });
    b.addEventListener("click", ()=>{
        getName(b);
    });
    c.addEventListener("click", ()=>{
        getName(c);
    });
</script>
</html>

In this example I've created three buttons for student1, student2 and student3 respectively. Now a named function getName is created in which a parameter is given button (One is free to take any other name). Further accessed the textContent of what is being passed as argument in prompt using interpolation.

The event listener is added on each button in which a arrow function is used to call the parameterized function getName every time clicked.