Top MNC JavaScript Interview Questions & Answers

Shallow copy: In the case of shallow copy when we copy the original object into the clone object then the clone object has the copy of the memory address of the original object. Means both points to the same memory address.

Both original object and cloned object internally point to the same referenced object. Since they point to the same memory address so if we changed the cloned object then changes would be reflected back to the original object because they point to the same memory address.

Both spread (...) and Object.assign() perform a shallow copy while the JSON methods carry a deep copy.

Using Object.assign operator: It takes the two parameters:
  • Empty object and
  • Original object
  •                                     
                                            let person = {
                                                name: "Ajay",
                                                lastname: "Kumar",
                                                address:{
                                                  city:"Haridwar",
                                                  state:"Uttarakhand",
                                                  country: "India",
                                                }
                                              };
                                              
                                              let person2 = Object.assign({}, person);
                                              person2.name="Vijay"
                                              person2.address.city = "Roorkee";
                                              person2.address.state="U.P."
                                              
                                              console.log("person 1 name is", person.address); 
                                              
                                              // ***************   Output 1 Person  **************//
    
                                              {
                                                firstName: 'Ajay',
                                                lastName: 'Kumar',
                                                address: {
                                                    city: 'Roorkee',
                                                    state: 'U.P.',
                                                    country :"India"
                                                }
                                              
                                              console.log("person 2 name is ", person2.address); 
    
                                              // ***************   Output 2 Person  **************//
    
                                              {
                                                firstName: 'Vijay',
                                                lastName: 'Kumar',
                                                address: {
                                                    city: 'Roorkee',
                                                    state: 'U.P.',
                                                    country :"India"
                                                }
                                            }
                                              
                                        
                                    
    In this example
  • First, create a new object named person.
  • Second, clone the person object using the Object.assign() method.
  • Third, change the first name and address information of the copiedPerson object.
  •                                     
                                           
                                            function Clipboard() {
                                                /* Get the text field */
                                                let copyText = document.getElementById("IdOfTextToCopy");
                                                
                                                /* Select the text field */
                                                copyText.select();
                                                
                                                /* Copy the text inside the text field */
                                                document.execCommand("copy");
                                                    
                                                /* Use below command to access the value of copied text */
                                                console.log(copyText.value);
                                            }
                                        
                                    

    Deep clone is a technique that is used to duplicate everything whenever we are cloning arrays and objects in JavaScript in order to avoid data loss.

    To copy an object in JavaScript, you have three options:

    1. Use the spread (...) syntax

    2. Use the Object.assign() method

    3. Use the JSON.stringify() and JSON.parse() methods
                                        
                                            const person={
                                                name:"Ajay",
                                                lastname:"Kumar"
                                            }
                                            
                                            // using spread operator 
                                            let p1 ={
                                                ...person
                                            }
                                            console.log("spread",p1)
                                            
                                            //using object assign
                                            let p2=Object.assign({},person)
                                            console.log("object assign",p2)
                                            
                                            //using JSON 
                                            let p3=   JSON.parse(JSON.stringify(person))
                                            console.log("JSON",p3)
                                        
                                    
    or
                                        
                                            var person = {
                                                name: "Ajay",
                                                lastname: "Kumar",
                                              };
                                              
                                              var person2 = Object.assign({}, person);
                                              
                                              person.name = "Vijay";
                                              
                                              console.log("person 1 name is", person.name); // Vijay
                                              
                                              console.log("person 2 name is ", person2.name); //Ajay
                                        
                                    
                                        
                                            let counter = 1;
                                            let copiedCounter = counter;
                                            copiedCounter = 2;
                                            
                                            console.log(counter);  //1
                                            
                                        
                                    
    However, if you use the assignment operator for a reference value, it will not copy the value.
                                        
                                            let person = {
                                                firstName: 'Ajay',
                                                lastName: 'Kumar'
                                            };
                                            let copiedPerson = person;
                                            
                                            copiedPerson.firstName = 'Vijay';
                                            console.log(person); 
                                            
                                             Output 
                                             { firstName: 'Vijay', lastName: 'Kumar' }
                                        
                                    
    Deep Copy Example :
                                        
                                            let person = {
                                                name: "Ajay",
                                                lastname: "Kumar",
                                                address:{
                                                  city:"Haridwar",
                                                  state:"Uttarakhand",
                                                  country:"India"
                                                }
                                              };
                                              
                                              let person2 = JSON.parse(JSON.stringify(person))
                                              
                                              person2.address.city = "Roorkee";
                                              person2.address.state="U.P."
                                              
                                              console.log("person 1 name is", person.address); // {city: 'Haridwar', state: 'Uttarakhand',country:"India"}
                                              
                                              console.log("person 2 name is ", person2.address); // {city: 'Roorkee', state: 'U.P.',country:"India"}
                                        
                                    

    In JavaScript, all functions are objects. They are the instances of the Function type. Because functions are objects, they have properties and methods like other objects.

    Functions properties :

    Each function has two important properties: length and prototype.
  • The length property determines the number of named arguments specified in the function declaration.
  • The length property determines the number of named arguments specified in the function declaration.
  • A function also has three important methods: call(), apply(), and bind().

  • Example :
                                        
                                            function add(x, y) {
                                                return x + y;
                                            }
                                            
                                            console.log(add.length); // 2
                                            console.log(add.prototype); // Object{}
                                        
                                    

    In JavaScript, the this keyword refers to the currently calling an object.

    Note : this is not a variable. It is a keyword. You cannot change the value of this.
                                        
                                            const person ={
                                                firstName:"Ajay",
                                                lastName:"Kumar",
                                                birth:1998,
                                                fullName:function(){
                                                    return this.firstName+" "+this.lastName;
                                                },
                                                currentAge:function(){
                                                    let myAge = new Date().getFullYear() - this.birth;
                                                    return myAge;
                                                }
                                            
                                            }
                                            console.log(person.fullName())  //Ajay kumar 
                                            console.log(person.currentAge()) //25
                                        
                                    
    In the example above, this refers to the person object.
    this.firstName means the firstName property of this.
    Same as:
    this.firstName means the firstName property of person.

    The this keyword refers to different objects depending on how it is used:
  • In an object method, this refers to the object.
  • Alone, this refers to the global object.
  • In a function, this refers to the global object.
  • In a function, in strict mode, this is undefined.
  • In an event, this refers to the element that received the event
  • Methods like call(), apply(), and bind() can refer this to any object.
  •     
            console.log(this === window); // true
    
            or 
    
            this.color= 'Red';
    console.log(window.color); // 'Red'
    
    or 
    
    function show() {
        "use strict";
        console.log(this === undefined); // true
    
        function display() {
            console.log(this === undefined); // true
        }
        display();
    }
    
    show();
        
    

    The call() method is a predefined JavaScript method.
    It can be used to invoke (call) a method with an owner object as an argument (parameter).

    With call(), an object can use a method belonging to another object.

    syntax:
                                        
                                            object.objectMethod.call( objectInstance, arguments )
                                        
                                    
    Parameters: It takes two parameters:
  • ObjectInstance : It is an object which we want to use explicitly(Clearly,decidely)
  • Arguments : It is arguments that we want to pass to the calling function
  •                                     
                                            const person = {
                                                fullName: function () {
                                                  return this.firstName + " " + this.lastName;
                                                },
                                                agePerson:function(){
                                                  let myAge = new Date().getFullYear()- this.age;
                                                  return myAge;
                                                }
                                              };
                                              const person1 = {
                                                firstName: "Ajay",
                                                lastName: "Kumar",
                                                age:1998,
                                              };
                                              const person2 = {
                                                firstName: "Vijay",
                                                lastName: "Kumar",
                                                age:1999,
                                              };
                                              
                                              console.log(person.fullName.call(person2)); //Vijay Kumar
                                              console.log(person.agePerson.call(person2)); //24
                                        
                                    
    The call() Method with Arguments

    The call() method can accept arguments:
                                        
                                            const person = {
                                                fullName: function(city,state, country) {
                                                  return this.firstName + " " + this.lastName + "," + city  +"," +state +"," + country;
                                                }
                                              }
                                              
                                              const person1 = {
                                                firstName:"Ajay",
                                                lastName: "Kumar"
                                              }
                                              
                                              console.log(person.fullName.call(person1, "Haridwar","Uttarakhand" ,"India"));
                                            //  Ajay Kumar,Haridwar,Uttarakhand,India
                                        
                                    

    The apply() method, you can write a method that can be used on different objects.

    syntax:
                                        
                                            object.objectMethod.apply(objectInstance, arrayOfArguments)
                                        
                                    
    Parameters: It takes two parameters:
  • ObjectInstance : It is an object which we want to use explicitly(clearly,decidely)
  • Arguments : It is arguments that we want to pass to the calling function
  •                                     
                                            const person = {
                                                fullName: function() {
                                                  return this.firstName + " " + this.lastName;
                                                }
                                              }
                                              
                                              const person1 = {
                                                firstName: "Ajay",
                                                lastName: "Kumar"
                                              }
                                              
                                              console.log(person.fullName.apply(person1))  // Ajay Kumar
                                        
                                    
    The apply() Method with Arguments

    The apply() method accepts arguments in an array:
                                        
                                            const person = {
                                                fullName: function(city,state, country) {
                                                  return this.firstName + " " + this.lastName + "," + city  +"," +state +"," + country;
                                                }
                                              }
                                              
                                              const person1 = {
                                                firstName:"Ajay",
                                                lastName: "Kumar"
                                              }
                                              
                                              console.log(person.fullName.apply(person1, ["Haridwar","Uttarakhand" ,"India"]));
                                            //  Ajay Kumar,Haridwar,Uttarakhand,India
                                        
                                    

    The difference is :
  • The call() method takes arguments separately.
  • The apply() method takes arguments as an array.

  • or

    Difference between the call() and apply() methods : The only difference is call() method takes the arguments separated by a comma while apply() method takes the array of arguments.
    # JavaScript call() Method JavaScript apply() Method
    1 It is used to write such a method that can be used on different objects. It is used to write methods, which can be used on different objects
    2 It is a Predefined Method in Javascript Its return value is the result of the calling function along provided this value and arguments.
    3 It is used for an object to use a method that belongs to a different object. We can use a list with this function instead of the array
    4 This method can also accept parameters. This method takes the parameter as an array

  • The bind() method creates a new function, when invoked, has the this sets to a provided value.
  • The bind() method allows an object to borrow a method from another object without making a copy of that method. This is known as function borrowing in JavaScript.
  •                                     
                                            const person = {
                                                firstName:"Ajay",
                                                lastName: "Kumar",
                                                fullName: function () {
                                                  return this.firstName + " " + this.lastName;
                                                }
                                              }
                                              
                                              const member = {
                                                firstName:"Vijay",
                                                lastName: "Kumar",
                                              }
                                              
                                              let fullName = person.fullName.bind(member);
                                              console.log(fullName)
                                              //   ƒ () {
                                              //    return this.firstName + " " + this.lastName;
                                              //  } 
                                        
                                    
    or
                                        
                                            const person = {
                                                firstName:"Ajay",
                                                lastName: "Kumar",
                                                fullName: function () {
                                                  return this.firstName + " " + this.lastName;
                                                }
                                              }
                                              
                                              const member = {
                                                firstName:"Vijay",
                                                lastName: "Kumar",
                                              }
                                              
                                              let fullName = person.fullName.bind(member);
                                              console.log(fullName()) // Vijay Kumar
                                              or
                                              let fullName = person.fullName.bind(member)();
                                              console.log(fullName) // Vijay Kumar
                                             
                                        
                                    
    this is lost
                                        
                                            let person = {
                                                name: 'Ajay Kumar',
                                                getName: function() {
                                                    console.log(this.name);   //Ajay Kumar
                                                }
                                              };
                                              
                                              console.log(person.getName())  //undefined
                                        
                                    

    In JavaScript, there are two types of variable scopes:

    1. Global Scope : Variables declared Globally (outside of any function) have Global Scope and Global variables can be accessed from anywhere in a program. Similar to function scope variables declared with var, let and const are quite similar when declared outside a block.Scope outside the outermost function attached to the window.

    2. Local Scope : Variables declared inside a function become local to the function. Local variables are created when a function starts and deleted when the function is executed. Local variables have Function Scope which means that they can only be accessed from within the function. Inside the function being executed.
                                        
                                            let globalLet = "This is a global variable";
    
                                            function fun() {
                                              let localLet = "This is a local variable";
                                            
                                              console.log(globalLet); // This is a global variable
                                              console.log(localLet); // This is a local variable
                                            }
                                            fun();
                                        
                                    
    or
                                        
                                            let globalLet = "This is a global variable";
    
    function fun() {
      let localLet = "This is a local variable";
    }
    fun();
    console.log(globalLet); // This is a global variable
    console.log(localLet); // localLet is not defined
                                        
                                    
    or Word of caution : Whenever you are declaring variables, always use the prefix let. If you don’t use the let keyword, then the variables are by default created in the global scope. For instance, in the above example.

                                        
                                            let globalLet = "This is a global variable";;
     
                                            function fun() {
                                               localLet = "This is a local variable";
                                            }
                                         
                                            fun();
                                              console.log(globalLet); // This is a global variable
                                              console.log(localLet); // This is a local variable
    
                                        
                                    
    Example : One of the most asked questions in interviews is the scenario where the global as well as local variable has the same name. Let’s see what happens then.
                                        
                                            let globalLet = "This is a global variable"
     
                                            function fun() {
                                              let globalLet = "This is a local variable"
                                            }
                                            fun();
                                            console.log(globalLet); // This is a global variable
    
                                            or 
    
                                            let globalLet = "This is a global variable";
     
                                            function fun() {
                                              let globalLet = "This is a local variable";
                                              console.log(window.globalLet); // This is a global variable
                                            }
                                            fun();
    
                                            
                                    
    Output: In this example, we have declared a local as well as global variable “globalLet”. What matters here is the scope in which we are accessing it. In this example, we are accessing it in global scope, so it will output the global variable as a local variable is not present in its scope.

    Example : What if we want to access the global variable instead of the local one here? Well, the window object comes to our rescue. All the global variables declared using the “var” keyword or without using any keyword are attached to the window object and thus we can access the global variable name as shown in the example below.
                                        
                                            let globalLet = "This is a global variable";
     
                                            function fun() {
                                              let globalLet = "This is a local variable";
                                              console.log(window.globalLet); // This is a global variable
                                            }
                                            fun();
                                            
                                    
    Example 4 :
                                        
                                            function fun(){
                                                function fun2(){
                                                     i = 100;
                                                }
                                                fun2();
                                                console.log(i); // 100
                                            }
                                            fun();
                                        
                                    
    Output : In this example, as we didn’t use the keyword let, the variable “i” was assumed to be declared in the global scope, and thus the output was 100.
    Example 5 :
                                        
                                            function fun(){
                                                function fun2(){
                                                    let i = 100;
                                                }
                                                fun2();
                                                console.log(i); // i is not defined
                                            }
                                            fun();
                                        
                                    
    Output : In this example, “i” became a local variable and thus was not accessible outside the scope of that function
    Example 6 :
                                        
                                            function fun(){
                                                if(true){
                                                    let i = 100;
                                                }
                                                console.log(i); // i is not defined
                                            }
                                            fun();
                                        
                                    
    Output : hence in the above example we get an error instead of the value 100. In earlier versions If we change the let to var we will get 100 as output as “if..else” block was not considered a block scope earlier, only functions were considered block scope.

    It is a JavaScript function passed to another function as an argument.

    A closure is a function having access to the parent scope, even after the parent function has closed.

    Closures offer a better and more concise way of writing code in JavaScript. They are created whenever a variable defined outside the current scope is accessed within the inner scope. It allows access to the outer function scope from within an inner function.

    Every time a function is created, closures are created as well. If you want to use a closure, define a function within another function and expose it.

    Example 1 :
                                    
                                        function hello(name) {
                                            var message = "hello " + name;
                                            return function hello() {
                                              console.log(message); // hello World
                                            };
                                          }
                                          
                                          //generate closure
                                          var helloWorld = hello("World");
                                          
                                          //use closure
                                          helloWorld();
                                    
                                
    Example 2 :
                                    
                                        function counterwrapper(){
                                            let count = 0;
                                            return function(){
                                                count++;
                                                console.log(count) //1  //2
                                            }
                                        }
                                        
                                        const updateCount= counterwrapper();
                                        updateCount();
                                        updateCount();
                                    
                                

    Example 1 :
                                    
                                        let name = 'Ajay';
    
                                        function greeting() { 
                                            let message = 'Hi';
                                            console.log(message + ' '+ name); // Hi Ajay 
                                        }
                                        greeting();
                                    
                                
  • The variable name is a global variable. It is accessible from anywhere including within the greeting() function.
  • The variable message is a local variable that is accessible only within the greeting() function.

  • Example 2 :
                                    
                                        function greeting() {
                                            let message = 'Hi';
                                        
                                            function sayHi() {
                                                console.log(message); // Hi
                                            }
                                        
                                            sayHi();
                                        }
                                        
                                        greeting();
                                    
                                
  • The greeting() function creates a local variable named message and a function named sayHi().
  • The sayHi() is the inner function that is available only within the body of the greeting() function.
  • The sayHi() function can access the variables of the outer function such as the message variable of the greeting() function.
  • Inside the greeting() function, we call the sayHi() function to display the message Hi.


  • JavaScript closures
    Let’s modify the greeting() function:
                                    
                                        function greeting() {
                                            let message = 'Hi';
                                        
                                            function sayHi() {
                                                console.log(message);  // Hi
                                            }
                                        
                                            return sayHi;
                                        }
                                        let hi = greeting();
                                        hi(); 
                                    
                                
    More JavaScript Closure example
    The following example illustrates a more practical example of closure.
                                    
                                        function greeting(message) {
                                            return function(name){
                                                 return message + ' ' + name;
                                            }
                                         }
                                         let sayHi = greeting('Hi');
                                         let sayHello = greeting('Hello');
                                         
                                         console.log(sayHi('Ajay')); // Hi Ajay
                                         console.log(sayHello('Ajay')); // Hello Ajay
                                    
                                
  • The greeting() function takes one argument named message and returns a function that accepts a single argument called name.
  • The return function returns a greeting message that is the combination of the message and name variables
  • The greeting() function behaves like a function factory. It creates sayHi() and sayHello() functions with the respective messages Hi and Hello.
  • The sayHi() and sayHello() are closures. They share the same function body but store different scopes.
  • In the sayHi() closure, the message is Hi, while in the sayHello() closure the message is Hello.
  • A JavaScript immediately invoked function expression is a function defined as an expression and executed immediately after creation.
    The following shows the syntax of defining an immediately invoked function expression:
                                    
                                        (function (){ 
    
                                            // Function Logic Here. 
    
                                            })();
    
                                            //*********  or   ***************//
    
                                            (() => {
                                                //...
                                            })();
                                    
                                
    Note that you can use an arrow function to define an IIFE:

    Example 1 :
                                    
                                        (function(){
                                            let x="Ajay"
                                            console.log(x) // Ajay
                                          })();
                                    
                                
    Example 2 :
                                    
                                        (function(a,b){
                                            console.log(a+b)  // 30
                                            return a + b;
                                        })(10,20);
                                    
                                
    Example 3 :
                                    
                                        (function() {
                                            var counter = 0;
                                        
                                            function add(a, b) {
                                                return a + b;
                                            }
                                        
                                            console.log(add(10,20)); // 30
                                        }());
                                    
                                
    Example 4 :
                                    
                                        (function() {
                                            var counter = 0;
                                        
                                            function add(a, b) {
                                                return a + b;
                                            }
                                        
                                            console.log(add(10,20)); // 30
                                        }());
                                    
                                
    Important Point
  • IIFE follow their own scope like any other function/variable in JavaScript.
  • The part of the name immediately invoked is sometimes confusing to new developers as they expect the IIFE to execute irrespective of function scope, this is wrong. For example, let us take the following example where the IIFE is defined within a function and will only be immediately invoked if we call it the Parent Function.
  • Example 5 :
                                    
                                        function myFunc()
                                        {
                                            console.log("Welcome to");  // Welcome to
                                            // This will be executed after executing the previous log.
                                            (function() { 
                                                console.log("Ajay Kumar"); // Ajay Kumar
                                            })();
                                            console.log("Hi There!");  // Hi There!
                                        }
                                          
                                        
                                        myFunc();
                                    
                                
  • 1. IIFEs have their own scope i.e. the variables you declare in the Function Expression will not be available outside the function.
  • 2. Similarly to other functions IIFEs can also be named or anonymous, but even if an IIFE does have a name it is impossible to refer/invoke it.
  • 3. IIFEs can also have parameters. For example,
  • Example 6 :
                                    
                                        // Declaring the parameter required.
                                        (function(dt) {
                                         console.log(dt.toLocaleTimeString());  // 6:12:57 PM
                                         // Passing the Parameter.
                                     })(new Date());
                                    
                                

    Arrow functions were introduced in ES6.

    Arrow functions allow us to write shorter function syntax . Arrow functions can only be used as a function expression.

    Arrow functions are anonymous functions i.e. they are functions without a name and are not bound by an identifier. Arrow functions do not return any value and can be declared without the function keyword. They are also called Lambda Functions. Syntax :
                                    
                                        let ajay = ()=> {
                                            return "Hello Ajay";
                                          }
                                          console.log(ajay()) // Hello Ajay
                                    
                                
                                    
                                      
      let ajay = ()=> "Hello Ajay";
      
      console.log(ajay())  // Hello Ajay 
                                    
                                
    Advantages of Arrow functions:
  • Arrow functions reduce the size of the code
  • The return statement and functional braces are optional for single-line functions.
  • It increases the readability of the code.

  • Arrow functions with parameters:
                                    
                                        const add= (x,y,z) => {
                                            console.log(x+y+z)  //60
                                        }
                                         
                                        add(10,20,30);
                                    
                                

    The rest parameter (...) allows a function to treat an indefinite number of arguments as an array. Other word it is the rest parameter. It stores n number of parameters as an array.
    Synatx :
                                    
                                        function sum(...args) {
                                            console.log(...args) // 4 10 100 66
                                            let sum = 0;
                                            for (let i of args) {
                                              sum += i;
                                            }
                                            return sum;
                                          }
                                          
                                          let x = sum(4, 10, 100, 66); 
                                          console.log(x);  //  180
                                    
                                

    Example 1 :
                                    
                                        function sum(a,b,c) {
                                            console.log(a,b,c) //  4 10 20 
                                          
                                          return a+b+c;  
                                        }
                                        
                                        let x = sum(4, 10,20,6); 
                                        console.log(x);  34
                                        
                                    
                                

    Example 2 :
                                    
                                        function sum(a,b,c,d) {
                                            console.log(a,b,c,d) //  4 10 undefined undefined
                                          
                                          return a+b+c+d;  // 14+undefined = NaN
                                        }
                                        
                                        let x = sum(4, 10); 
                                        console.log(x);  //NaN
                                    
                                
    Example 3 :
                                    
                                        // rest with function and other arguments
                                        function fun(a, b, ...c) {
                                          console.log(`${a} ${b}`); // Ajay Vijay
                                          console.log(c);  // [ "Lalit", "Sagar", "Bhuvnesh" ]
                                          console.log(...c);  // Lalit Sagar Bhuvnesh
                                          console.log(c[0]); // Lalit
                                          console.log(c.length); //3
                                          console.log(c.indexOf("Lalit")); //0
                                        }
                                        fun("Ajay", "Vijay", "Lalit", "Sagar", "Bhuvnesh");
                                    
                                

    JavaScript rest parameters and arrow function

    An arrow function does not have the arguments object. Therefore, if you want to pass some arguments to the arrow function, you must use the rest parameters. See the following example:
                                
                                    const combine = (...args) => {
                                        return args.reduce(function (prev, curr) {
                                          return prev + ' ' + curr;
                                        });
                                      };
                                      
                                      let message = combine('JavaScript', 'Rest', 'Parameters'); // =>
                                      console.log(message); // JavaScript Rest Parameters
                                
                            

    The combine() function is an arrow that takes an indefinite number of arguments and concatenates these arguments.

  • A callback is a function passed into another function as an argument to be executed later.
  • A high-order function is a function that accepts another function as an argument.
  • Callback functions can be synchronous or asynchronous.

  • Basic Example :
                                
                                    function myDisplayer(ajay){
                                        console.log("Ajay" +" "+ ajay)
                                      }
                                      
                                      function myFirst() {
                                        myDisplayer("Hello");  // Ajay Hello
                                      }
                                      
                                      function mySecond() {
                                        myDisplayer("Goodbye"); // Ajay Goodbye
                                      }
                                      myFirst();
                                      mySecond();
                                
                            

    Example 1 :
                              
                                function myDisplayer(result){
                                    console.log("Result" +" "+ result) // Result 10
                                  }
                                  
                                  function myCalculator(num1,num2) {
                                      let sum = num1+  num2;
                                      return sum;
                                  }
                                  
                                  let result=myCalculator(5,5);
                                  myDisplayer(result);
                              
                          

    Example 2 :
                            
                                function myDisplayer(result){
                                    console.log("Result" +" "+ result) // Result 10
                                  }
                                  
                                  function myCalculator(num1,num2) {
                                      let sum = num1+  num2;
                                      myDisplayer(sum);
                                  }
                                  
                                  myCalculator(5,5);
                            
                        

  • The problem with the first example above, is that you have to call two functions to display the result.
  • The problem with the second example, is that you cannot prevent the calculator function from displaying the result.
  • Now it is time to bring in a callback.

  • Example JavaScript Callbacks
                            
                                function myDisplayer(result) {
                                    console.log("Result" + " " + result); // Result 10
                                  }
                                  
                                  function myCalculator(num1, num2, myCallback) {
                                    let sum = num1 + num2;
                                    myCallback(sum);
                                  }
                                  
                                  myCalculator(5, 5, myDisplayer);
                            
                        

    In the example above, myDisplayer is a called a callback function.

    It is passed to myCalculator() as an argument.

    Another Example :
                            
                                function mainFunction(callback) {
                                    console.log("Performing operation...");
                                  
                                    setTimeout(function () {
                                      callback("Operation complete");
                                    }, 2000);
                                  }
                                  
                                  // Define the callback function
                                  function callbackFunction(result) {
                                    console.log("Result: " + result);
                                  }
                                  
                                  // Call the main function with the callback function
                                  mainFunction(callbackFunction);
                                  
                                  //Output 
                                  Performing operation...
                                   Operation complete
                            
                            

    A higher order function is a function that takes one or more functions as arguments, or returns a function as output.
    There are various built in HOFs, and some of the most common ones are map(), filter() and reduce().
    Example 1 :
                                    
                                        // Callback function, passed as a parameter in the higher order function
                                        function callbackFunction(){
                                            console.log('I am  a callback function'); //2 time I am  a callback function
                                        }
                                        
                                        // higher order function
                                        function higherOrderFunction(func){
                                            console.log('I am higher order function') //1 time => I am higher order function
                                            func()
                                        }
                                        
                                        higherOrderFunction(callbackFunction);
                                    
                                    

    Needs of Higher Order Arrow Function:
  • In a general way, the programmer instructs on how to perform the function rather than what is needed which increases the length of the code and makes it error-prone.
  • Whereas in the Higher Order Arrow Functions implementation, the code is much short, concise, succinct, easy to debug, and focuses on what is required rather than how to achieve it.
  • We can directly work with the current value instead of accessing it individually using its index (i.e arr[0]).
  • There is no need to create a predefined array and push back the changes.


  • Example 2 :
                                    
                                        const arr = [1, 2, 3, 4, 5];
                                        const output = arr.map((num) => num += 10)
                                        console.log(arr); // [1, 2, 3, 4, 5]
                                        console.log(output); // [11, 12, 13, 14, 15]
                                    
                                    

    In the above example, arr is an array with five elements: 1, 2, 3, 4, and 5. map is a method that we use to apply a function to each element in an array, and it returns a new array with the modified elements.

    The callback function that is being passed to map uses the arrow function syntax, and it takes a single argument num. This function adds 10 to num (every element in the array) and returns the result.

    Example 3 :
                                        
                                            const users = [
                                            {firstName: 'John', lastName: 'Doe', age: 25},
                                            {firstName: 'Jane', lastName: 'Doe', age: 30},
                                            {firstName: 'Jack', lastName: 'Doe', age: 35},
                                            {firstName: 'Jill', lastName: 'Doe', age: 40},
                                            {firstName: 'Joe', lastName: 'Doe', age: 45},
                                        ]
                                        
                                        const result = users.map((user) => user.firstName + ' ' + user.lastName)
                                        console.log(result); // ['John Doe', 'Jane Doe', 'Jack Doe', 'Jill Doe', 'Joe Doe']
                                        
                                        

    In the above code, users is an array of objects representing users. Each object has three properties: firstName, lastName, and age.
    We are mapping over each user using the map() method to extract the properties firstName and lastName.
    The callback function takes a single argument user which represents an element in the users array (an object).
    The function concatenates the firstName and lastName properties of the user object, and returns the result.

    Currying is a process in functional programming in which we can transform a function with multiple arguments into a sequence of nesting functions. It returns a new function that expects the next argument inline. It helps to avoid passing the same variable again and again, also in creating high order functions.

                                    
                                        function addcn(a, b, c) {
                                            return a + b + c;
                                        }
                                        
                                        
                                        
                                        function addcn_curried(a)//curried function {
                                        
                                            return function (b) {
                                                return function (c) {
                                                    return a + b + c
                                                }
                                            }
                                        }
                                        
                                        let res = addcn(1, 2, 3);
                                        console.log(res);
                                        
                                        let mc1 = addcn_curried(1);
                                        let mc2 = mc1(2);
                                        let res2 = mc2(3);
                                        console.log(res2);
                                        
                                        let res3 = addcn_curried(1)(2)(3);
                                        console.log(res3);
    
    
                                        //Output : 
                                        
                                        6
                                        6
                                        6
                                    
                                    

    Whenever we create a function using JavaScript, JavaScript engine adds a prototype property inside a function, Prototype property is basically an object (also known as Prototype object), where we can attach methods and properties in a prototype object, which enables all the other objects to inherit these methods and properties.
    Example 1 :
                                    
                                        // function constructor
                                        function Person(name, job, yearOfBirth){   
                                            this.name= name;
                                            this.job= job;
                                            this.yearOfBirth= yearOfBirth;
                                        }
                                        // this will show Person's prototype property.
                                        console.log(Person.prototype);
    
                                        Output :
                                        constructor: ƒ Person(name, job, yearOfBirth)
    [[Prototype]]: Object
                                    
                                    


    Example 2 :
                                        
                                            let user = {
                                                getFullName: function () {
                                                  return this.firstName + " " + this.lastName;
                                                },
                                                getAge: function () {
                                                  let myAge = new Date().getFullYear() - this.age;
                                                  return myAge;
                                                },
                                              };
                                              
                                              let student = {
                                                firstName: "Ajay",
                                                lastName: "Kumar",
                                                age: 1998,
                                              };
                                              
                                              let teacher = {
                                                firstName: "Gunjit",
                                                lastName: "Chauhan",
                                                age: 1990,
                                              };
                                              
                                              student.__proto__=user;
                                              teacher.__proto__=user;
                                              
                                              console.log(student.getFullName()); // Ajay kumar
                                              console.log(student.getAge());   // 25
                                              console.log(teacher.getFullName());  // Gunjit Chauhan
                                              console.log(teacher.getAge()); //33
                                              
                                        
                                        


    How to add by deafult property of object prototype
    Yes , We can add property Object.protoype.myInfo= "I am Full Stack Web Developer"

    Execution Context : Everything in JavaScript is wrapped inside Execution Context, which is an abstract concept (can be treated as a container) that holds the whole information about the environment within which the current JavaScript code is being executed.

    or

    When the JavaScript engine executes the JavaScript code, it creates execution contexts.
    Each execution context has two phases:
    1. Creation Phase
    2. Execution Phase

    1. Creation phase: In this phase, the JavaScript engine creates the execution context and sets up the script's environment. It determines the values of variables and functions and sets up the scope chain for the execution context.
    2. Execution phase: In this phase, the JavaScript engine executes the code in the execution context. It processes any statements or expressions in the script and evaluates any function calls.

    Call Stack : When a program starts execution JavaScript pushes the whole program as global context into a stack which is known as Call Stack and continues execution. Whenever JavaScript executes a new context and just follows the same process and pushes to the stack. When the context finishes, JavaScript just pops the top of the stack accordingly.
    stack
    When JavaScript completes the execution of the entire code, the Global Execution Context gets deleted and popped out from the Call Stack making the Call stack empty.

    or

    A call stack is a way for the JavaScript engine to keep track of its place in code that calls multiple functions. It has the information on what function is currently being run and what functions are invoked from within that function…

    Also, the JavaScript engine uses a call stack to manage execution contexts:
  • Global execution context
  • function execution contexts
  • The call stack works based on the LIFO principle i.e., last-in-first-out.

    When you execute a script, the JavaScript engine creates a global execution context and pushes it on top of the call stack.

    Whenever a function is called, the JavaScript engine creates a function execution context for the function, pushes it on top of the call stack, and starts executing the function.

    If a function calls another function, the JavaScript engine creates a new function execution context for the function being called and pushes it on top of the call stack.

    When the current function completes, the JavaScript engine pops it off the call stack and resumes the execution where it left off.

    The script will stop when the call stack is empty.

    JavaScript single-threaded model

    JavaScript is a single-threaded programming language. This means that JavaScript runs in one line at a time manner and there is no possibility of running code in parallel.

    The JavaScript engine executes a script from the top of the file and works its way down. It creates the execution contexts, pushes, and pops functions onto and off the call stack in the execution phase.

    If a function takes a long time to execute, you cannot interact with the web browser during the function’s execution because the page hangs.

    A function that takes a long time to complete is called a blocking function. Technically, a blocking function blocks all the interactions on the webpage, such as mouse click.

    Event Loop :
    An event loop is something that pulls stuff out of the queue and places it onto the function execution stack whenever the function stack becomes empty.


    # Debouncing Throttling
    1 Debouncing waits for a certain time before invoking the function again. Throttling limits the number of times the function can be called over a certain period.
    2 Ensures that the function is called only once, even if the event is triggered multiple times. Ensures that the function is called at a regular interval, even if the event is triggered multiple times.
    3 Useful when you want to delay the invocation of a function until a certain period of inactivity has passed. Useful when you want to list the Frequency of function calls.
    4 Eg. You can debounce an async API request function that is called every time the user types in an input field. Eg. You can throttle a slide change Function that is called every time the user clicks a button in a carousel.