Javascript Interview Questions

1. What is JavaScript ?

The JavaScript language is commonly used for coding interactive web pages and web applications.

JavaScript has the following key features:

  • Client-Side Scripting
  • Object-Oriented Programming (OOP)
  • Event-Driven Programming
  • Versatility
  • Libraries and Frameworks
  • Asynchronous Programming
  • Syntax and Grammar

  • 2. What are the data types in JavaScript ?

    There are six primitive data types in JavaScript:

  • string
  • number
  • boolean
  • null
  • undefined
  • symbol
  • and one complex data type: object

  • 3. Difference between let, const, and var ?

    With ES6, let and const become block-scoped variables, while var becomes function-scoped. The let type allows for assignment, the const type is for variables that don't change, and the var type is for variables with function scope.

    let

    let x = 10;
    x = 20; // Valid: x can be reassigned a new value
    
    let y = 5;
    let y = 15; // Invalid: Trying to redeclare y within the same block 

    const

    const PI = 3.14;
    PI = 3.14159; // Invalid: Trying to reassign a new value to PI
    
    const myArray = [1, 2, 3];
    myArray.push(4); // Valid: Modifying the array by adding a new element 

    var

    var a = 5;
    var a = 10; // Valid: Redeclaring a within the same scope
    
    function example() {
      var b = 15;
      if (true) {
        var b = 20; // Same variable b, as var does not have block scope
        console.log(b); // Output: 20
      }
      console.log(b); // Output: 20
    }
    
    example(); 
    Learn More


    4. JavaScript hoisting ?

    The hoisting process in JavaScript involves moving variable and function declarations to the top of their containing scope during compilation.

    var x1; 
    x1 = 5;
    console.log(x1); // 5
    
    x2 = 10;
    console.log(x2); // 10
    var x2; 
    
    var x3;
    console.log(x3); // undefined
    x3 = 15;
    
    x4 = 20;
    var x4;
    console.log(x4); // 20
    
    var x5;
    console.log(x5); // undefined
    
    console.log(x6); // undefined
    var x6 = 25;
    
    y1 = "25";
    let y1;
    console.log(y1); // ReferenceError: Cannot access 'y1' before initialization
    
    z1 = "30";
    const z1;
    console.log(z1); // SyntaxError: Missing initializer in const declaration 
    Learn More


    5. JavaScript closure?

    When a function is defined within another function in JavaScript, the inner function has access to the outer function's variables even after it has finished executing.

    function outerFunction() {
      var outerVariable = "I'm from the outer function";
    
      function innerFunction() {
        console.log(outerVariable);
      }
    
      return innerFunction;
    }
    
    var closure = outerFunction();
    closure(); // Output: "I'm from the outer function" 
    Learn More


    6. JavaScript event delegation ?

    An event delegation technique involves adding an event listener to a parent element to handle events occurring on its children. As a result, the number of event handlers is minimized and performance is improved.

    <!DOCTYPE html>
    <html>
    <head>
      <title>Event Delegation Example</title>
    </head>
    <body>
      <ul id="myList">
        <li>Item 1</li>
        <li>Item 2</li>
        <li>Item 3</li>
        <li>Item 4</li>
        <li>Item 5</li>
      </ul>
    
      <script>
        // Attach the event handler to the parent element
        const list = document.getElementById('myList');
        list.addEventListener('click', function(event) {
          // Check if the clicked element is an <li> element
          if (event.target.nodeName === 'LI') {
            // Get the text content of the clicked <li> element
            const text = event.target.textContent;
            console.log('Clicked:', text);
          }
        });
      </script>
    </body>
    </html> 


    7. Difference between === and == operators ?

    When == is used, the equality is compared after type conversion while === is used to check for strict equality when no type conversion is involved.

    //Strict Equality (===)
    console.log(5 === 5);        // true
    console.log("5" === 5);      // false (different types)
    console.log(5 === "5");      // false (different types)
    console.log(true === true);  // true
    console.log(null === undefined); // false (different types)
    
    //Loose Equality (==)
    console.log(5 == 5);        // true
    console.log("5" == 5);      // true (converted string to number)
    console.log(5 == "5");      // true (converted string to number)
    console.log(true == 1);     // true (converted boolean to number)
    console.log(null == undefined); // true (special case) 
    Learn More


    8. When an event is created in JavaScript, how can you prevent its default behavior ?

    In JavaScript, you can prevent the default behavior of an event by using the event.preventDefault() method.

    <!DOCTYPE html>
    <html>
    <head>
      <title>Event.preventDefault() Example</title>
    </head>
    <body>
      <a href="https://www.techstackguru.com/" id="myLink">Click me</a>
    
      <script>
        document.getElementById("myLink").addEventListener("click", function(event) {
          event.preventDefault(); // Prevent the link from navigating to a new page
          console.log("Link clicked, but default behavior prevented");
        });
      </script>
    </body>
    </html> 


    9. Different types of errors in JavaScript ?

    In JavaScript, there are several types of errors, such as syntax errors, runtime errors, and logical errors.

    //Syntax Errors
    if (x == 5 {   // Missing closing parenthesis
      console.log("x is equal to 5");
    }
    
    //Reference Errors
    console.log(x);   // ReferenceError: x is not defined
    
    //Type Errors
    var x = "Hello";
    console.log(x.toUpperCase());   // TypeError: x.toUpperCase is not a function
    
    //Range Errors
    var arr = [1, 2, 3];
    console.log(arr[5]);   // RangeError: Invalid array length
    
    //Logic Errors
    function calculateAverage(numbers) {
      var sum = 0;
      for (var i = 0; i <= numbers.length; i++) {
          sum += numbers[i];
      }
      return sum / numbers.length;
    }
    
    var result = calculateAverage([1, 2, 3]);
    console.log(result);   // NaN (Not a Number)
    
    //EvalErrors
    eval("x ++ y");   // EvalError: invalid increment operand
    
    //URIErrors
    decodeURI('%');   // URIError: URI malformed 


    10. What is the use of this keyword in JavaScript ?

    Programmers use the this keyword to refer to a methods object or the context within which it is called.

    const employee = {
      firstName: "Vishal",
      lastName : "Torgal",
      getFullName : function() {
        return this.firstName + ' ' + this.lastName;
      }
    };
    
    console.log(employee.getFullName()); //Vishal Torgal 


    11. What is prototypal inheritance in JavaScript ?

    An object can inherit properties and methods from another object via a prototype chain in JavaScript. When an objects properties or methods are not available, it uses the prototype object as a fallback.

    //Creating objects with their own properties:
    const adam = Object.create(personPrototype);
    adam.name = "Vishal";
    adam.age = 19;
    console.log(adam.name); // Output: Vishal
    console.log(adam.age); // Output: 19 


    12. Difference between synchronous and asynchronous programming ?

    Asynchronous programming allows tasks to be executed concurrently without blocking execution flow, in contrast to synchronous programming which executes tasks one after the other in a blocking manner.

    //Synchronous Programming:
    console.log("Start");
    
    function synchronousTask() {
      console.log("Synchronous Task");
    }
    
    synchronousTask();
    
    console.log("End");
    
    //Output 
    Start
    Synchronous Task
    End
    
    
    //Asynchronous Programming:
    console.log("Start");
    
    function asynchronousTask() {
      setTimeout(function() {
        console.log("Asynchronous Task");
      }, 2000);
    }
    
    asynchronousTask();
    
    console.log("End");
    
    //Output
    Start
    End
    Asynchronous Task  


    13. In JavaScript, how do you create a new object ?

    JavaScript allows you to create new objects by using

  • object literals
  • new keywords with constructor functions
  • Object.create() method
  • //Object Literal
    const person = {
      name: "Katha",
      age: 8,
      greet: function() {
        console.log(this.name);
      }
    };
    
    person.greet() //Katha
    
    //Constructor Function
    function Person(name, age) {
      this.name = name;
      this.age = age;
      this.greet = function() {
        console.log(this.name);
      };
    }
    
    const obj = new Person("Astha", 13);
    obj.greet(); //Astha
    
    //Object.create()
    const personPrototype = {
      greet: function() {
        console.log(this.name);
      }
    };
    
    const obj = Object.create(personPrototype);
    obj.name = "Kanishka";
    obj.age = 2;
    
    obj.greet(); //Kanishka
    


    14. How does JavaScripts bind() method work ?

    Whenever the bind() method is invoked, it will set the this keyword to a specific value, regardless of how it is called.

    const person = {
      firstName: 'Aarush',
      lastName: 'P',
    };
    
    // Creating a function
    function hello(greeting) {
      console.log(greeting + ' ' + this.firstName + ' ' + this.lastName);
    }
    
    // Using bind() to bind the function to the person object
    const boundHello = hello.bind(person);
    
    // Calling the bound function
    boundHello('Hi'); //Hi Aarush P 

    15. How does JavaScripts map() method work ?

    In JavaScript, the map() method performs transformations on each element of an array and returns a new array with the results.

    // Original array
    const num = [1, 2, 3, 4, 5];
    
    // Using map() to double each number
    const doubledNum = num.map((num) => num * 2);
    
    console.log(doubledNum); 

    16. In JavaScript, how do you determine whether a variable is an array ?

    The Array.isArray() method can be used to determine whether a variable is an array.

    // Check if a value is an array
    console.log(Array.isArray([1, 2, 3])); // true
    console.log(Array.isArray('Hello'));   // false
    console.log(Array.isArray({ a: 1 }));  // false
    
    // Check if a variable is an array
    const fruits = ['apple', 'banana', 'orange'];
    console.log(Array.isArray(fruits));    // true
    
    const person = { name: 'John', age: 25 };
    console.log(Array.isArray(person));    // false 

    17. What is the process of cloning an object in JavaScript ?

    JavaScript provides several methods for cloning objects, including Object.assign(), spread syntax, or JSON.parse(JSON.stringify()).

    //Spread Operator(...)
    const originalObj = { name: 'John', age: 25 };
    const clonedObj = { ...originalObj };
    console.log(clonedObj); //{ name: 'John', age: 25 }
    
    
    //Object.assign()
    const originalObj = { name: 'John', age: 25 };
    const clonedObj = Object.assign({}, originalObj);
    console.log(clonedObj); //{ name: 'John', age: 25 }
    
    
    //JSON.parse() and JSON.stringify()
    const originalObj = { name: 'John', age: 25 };
    const clonedObj = JSON.parse(JSON.stringify(originalObj));
    console.log(clonedObj); //{ name: 'John', age: 25 } 

    18. Describe the JavaScript concept of event bubbling ?

    In the DOM hierarchy, an event triggered on a particular element, such as a button, will also trigger on all its parents. The propagation of an event from the innermost element to its ancestors is called event bubbling.

    HTML

    <div id="outer">
    <div id="inner">
      <button id="btn">Click me!</button>
    </div>
    </div> 

    Javascript

    document.getElementById("outer").addEventListener("click", function() {
      console.log("Outer div clicked!");
    });
    
    document.getElementById("inner").addEventListener("click", function() {
      console.log("Inner div clicked!");
    });
    
    document.getElementById("btn").addEventListener("click", function() {
      console.log("Button clicked!");
    }); 

    19. How does the querySelector() method work ?

    When a CSS selector is specified, querySelector() will select the first element matching that CSS selector.

    //HTML
    <div id="container">
    <h1>Title</h1>
    <p class="content">Lorem ipsum dolor sit amet.</p>
    <p class="content">Consectetur adipiscing elit.</p>
    </div>
    
    //JavaScript
    // Select the first <p> element with the class "content"
    const firstParagraph = document.querySelector('p.content');
    
    // Log the text content of the selected element
    console.log(firstParagraph.textContent);
    
    //Output
    Lorem ipsum dolor sit amet. 

    20. How do JavaScript arrow functions work ?

    JavaScripts arrow functions enable function expressions to be written in a concise manner. Their syntax is shorter, and they inherit this value from their surrounding scopes.

    // Regular function expression
    const addRegular = function (a, b) {
      return a + b;
    };
    
    console.log(addRegular(2, 3)); // Output: 5
    
    // Arrow function
    const addArrow = (a, b) => a + b;
    
    console.log(addArrow(2, 3)); // Output: 5

    21. In JavaScript, how can you convert a string to a number ?

    JavaScript provides functions that can be used to convert strings into numbers, such as parseInt() or parseFloat().

    let str = "42";
    let num = parseInt(str);
    
    console.log(num); // Output: 42
    console.log(typeof num); // Output: number
    
    let str = "3.14";
    let num = parseFloat(str);
    
    console.log(num); // Output: 3.14
    console.log(typeof num); // Output: number

    22. How does setTimeout() work ?

    When setTimeout() is invoked, a function or code snippet will run after a specified period of time.

    function greet() {
      console.log("Hello, world!");
    }
    
    setTimeout(greet, 2000); // Schedule the greet function to run after 2000 milliseconds (2 seconds) 

    23. How does querySelectorAll() work ?

    QuerySelectorAll() returns a static NodeList containing all elements matching a specified CSS selector.

    <!DOCTYPE html>
    <html>
    <head>
      <title>querySelectorAll Example</title>
    </head>
    <body>
      <h1>querySelectorAll Example</h1>
      <ul>
        <li class="fruit">Apple</li>
        <li class="animal">Tiger</li>
        <li class="fruit">Orange</li>
      </ul>
    
      <script>
        // Select all elements with class "fruit" and change their text color
        const fruits = document.querySelectorAll('.fruit');
        fruits.forEach(fruit => {
         console.log(fruit)
        });
      </script>
    </body>
    </html 
    
    //Console
    Apple
    Orange  

    24. In JavaScript, what does the async and await keyword mean ?

    Async and await keywords enable asynchronous code to appear synchronous, allowing promise handling and handling asynchronous operations more easily.

    function resolveAfter2Seconds() {
      return new Promise(resolve => {
        setTimeout(() => {
          resolve('Resolved after 2 seconds');
        }, 2000);
      });
    }
    
    async function asyncFunction() {
      console.log('Async function started');
      
      try {
        const result = await resolveAfter2Seconds();
        console.log(result);
        console.log('Async function completed');
      } catch (error) {
        console.error('Error:', error);
      }
    }
    
    asyncFunction();
    
    //Output
    Async function started
    Resolved after 2 seconds
    Async function completed  

    25. If you have an array-like object, how can you convert it to an array ?

    The array-like object can be converted to an array using the Array.from() method or by spreading it into an array [...object].

    //Array.from()
    const arrayLikeObject = { 0: 'foo', 1: 'bar', length: 2 };
    const array = Array.from(arrayLikeObject);
    console.log(array); // Output: ['foo', 'bar']
    
    //Spread syntax (...)
    const arrayLikeObject = { 0: 'foo', 1: 'bar', length: 2 };
    const array = [...arrayLikeObject];
    console.log(array); // Output: ['foo', 'bar']
    
    //Array.prototype.slice()
    const arrayLikeObject = { 0: 'foo', 1: 'bar', length: 2 };
    const array = Array.prototype.slice.call(arrayLikeObject);
    console.log(array); // Output: ['foo', 'bar']
    
    //Array.prototype.concat()
    const arrayLikeObject = { 0: 'foo', 1: 'bar', length: 2 };
    const array = Array.prototype.concat.apply([], arrayLikeObject);
    console.log(array); // Output: ['foo', 'bar']  

    26. How does JavaScript's reduce() method work ?

    A JavaScript reduce() method reduces an array to a single value by executing a reducer function on each element.

    const numbers = [1, 2, 3, 4, 5];
    
    const sum = numbers.reduce((accumulator, currentValue) => {
      return accumulator + currentValue;
    }, 0); //0 is initial value
    
    console.log(sum); // Output: 15 

    27. Is there a way to handle JavaScript errors ?

    To handle exceptions in JavaScript, try-catch statements can be used.

    try {
      // Code that may potentially throw an error
      const result = someFunction();
      console.log(result);
    } catch (error) {
      // Code to handle the error
      console.error('An error occurred:', error);
    } 

    28. Difference between Local Storage, Session Storage, and Cookies in JavaScript ?

    Session Storage

    In sessionStorage, you can only access data within the current tab or window, and it will be cleared when you close it.

    Local Storage

    As another type of web storage, localStorage is capable of retaining data even after the user closes the browser.

    Cookies

    Cookie files are small pieces of data stored in the browser of a user. In addition to their expiration date, they can be accessed from both the client and the server.

    // Example using session storage
    sessionStorage.setItem('username', 'John');
    console.log(sessionStorage.getItem('username')); // Output: John
    
    // Example using local storage
    localStorage.setItem('username', 'John');
    console.log(localStorage.getItem('username')); // Output: John
    
    // Example using cookies
    document.cookie = 'username=John; expires=Thu, 31 Dec 2023 23:59:59 UTC; path=/';
    console.log(document.cookie); // Output: username=John  

    29. In JavaScript, how do you convert an object into a JSON string ?

    If you want to convert an object to a JSON string, you can use the JSON.stringify() method.

    const person = {
      name: 'John',
      age: 30,
      city: 'New York'
    };
    
    const jsonString = JSON.stringify(person);
    
    console.log(jsonString); //{"name":"John","age":30,"city":"New York"} 

    30. In JavaScript arrays, why is push() called ?

    When push() is used, one or more elements are added to the end of an array and the size of the array is recalculated.

    const fruits = ['apple', 'banana', 'orange'];
    
    fruits.push('mango');
    console.log(fruits); // Output: ['apple', 'banana', 'orange', 'mango']
    
    fruits.push('strawberry', 'grape');
    console.log(fruits); // Output: ['apple', 'banana', 'orange', 'mango', 'strawberry', 'grape'] 

    31. In JavaScript, how do you remove an element from an array ?

    JavaScript provides methods like splice(), pop(), shift() and filter() for removing elements from arrays.

    //splice()
    const fruits = ['apple', 'banana', 'orange', 'mango'];
    
    fruits.splice(1, 1); // Remove 1 element at index 1
    console.log(fruits); // Output: ['apple', 'orange', 'mango']
    
    //pop()
    const fruits = ['apple', 'banana', 'orange'];
    
    const removedElement = fruits.pop();
    console.log(removedElement); // Output: 'orange'
    console.log(fruits); // Output: ['apple', 'banana']
    
    //shift()
    const fruits = ['apple', 'banana', 'orange'];
    
    const removedElement = fruits.shift();
    console.log(removedElement); // Output: 'apple'
    console.log(fruits); // Output: ['banana', 'orange']
    
    //filter()
    const fruits = ['apple', 'banana', 'orange'];
    
    const filteredFruits = fruits.filter(fruit => fruit !== 'banana');
    console.log(filteredFruits); // Output: ['apple', 'orange'] 

    32. In JavaScript, what is the difference between a call method and an apply method ?

    Call() and apply() invoke a function with specific arguments andthis value. There is a difference in how arguments are passed: call() accepts individual arguments, while apply() accepts an array-like object.

    //call
    function greet(name) {
      console.log({name}); //{ name: 'John' }
    }
    
    greet.call(null, 'John'); 
    
    //apply
    function greet(name) {
      console.log({name}); //{ name: 'Dark' }
    }
    
    greet.apply(null, ['Dark']); 

    33. In JavaScript, how do you convert a number to a string ?

    To convert a number to a string, use the toString() method or concatenate it with an empty string.

    //toString()
    let number = 42;
    let stringNumber = number.toString();
    console.log(typeof stringNumber); // "string"
    console.log(stringNumber); // "42" 
    
    //Using string concatenation
    let number = 42;
    let stringNumber = '' + number;
    console.log(typeof stringNumber); // "string"
    console.log(stringNumber); // "42"  

    34. Why is the Math object used in JavaScript ?

    JavaScript offers built-in mathematical functions and constants through the Math object.

    // Example 1: Calculating the square root
    let number = 16;
    let squareRoot = Math.sqrt(number);
    console.log(squareRoot); // 4
    
    // Example 2: Generating a random number
    let randomNum = Math.random();
    console.log(randomNum); // Random number between 0 (inclusive) and 1 (exclusive)
    
    // Example 3: Rounding a number
    let floatNum = 3.14;
    let roundedNum = Math.round(floatNum);
    console.log(roundedNum); // 3
    
    // Example 4: Using mathematical constants
    let circleArea = Math.PI * Math.pow(radius, 2);
    console.log(circleArea); // Area of a circle with radius 'radius'  

    35. In JavaScript, how do you remove duplicate elements from an array ?

    Arrays can be filtered using the filter() method with the indexOf() function, or converting them to Sets and then back to arrays.

    //Set
    let array = [1, 2, 3, 4, 4, 5, 6, 6];
    let uniqueArray = [...new Set(array)];
    console.log(uniqueArray); // [1, 2, 3, 4, 5, 6]
    
    //filter() and indexOf()
    let array = [1, 2, 3, 4, 4, 5, 6, 6];
    let uniqueArray = array.filter((value, index) => array.indexOf(value) === index);
    console.log(uniqueArray); // [1, 2, 3, 4, 5, 6]
    
    //reduce() and includes()
    let array = [1, 2, 3, 4, 4, 5, 6, 6];
    let uniqueArray = array.reduce((acc, value) => {
      if (!acc.includes(value)) {
        acc.push(value);
      }
      return acc;
    }, []);
    console.log(uniqueArray); // [1, 2, 3, 4, 5, 6]  

    36. In JavaScript, what is a generator function ?

    Generator functions allow you to generate a series of values over time by pausing and resuming their execution.

    function* numberGenerator() {
      yield 1;
      yield 2;
      yield 3;
    }
    
    const generator = numberGenerator();
    console.log(generator.next()); // { value: 1, done: false }
    console.log(generator.next()); // { value: 2, done: false }
    console.log(generator.next()); // { value: 3, done: false }
    console.log(generator.next()); // { value: undefined, done: true } 

    37. In JavaScript, how do you determine whether an object has a specific property ?

    In order to check whether an object has a specific property, you can use hasOwnProperty() or the in operator.

    //hasOwnProperty()
    const obj = {
      prop1: 'value1',
      prop2: 'value2'
    };
    
    if (obj.hasOwnProperty('prop1')) {
      console.log('obj has prop1');
    } else {
      console.log('obj does not have prop1');
    }
    
    //in operator
    const obj = {
      prop1: 'value1',
      prop2: 'value2'
    };
    
    if ('prop1' in obj) {
      console.log('obj has prop1');
    } else {
      console.log('obj does not have prop1');
    } 

    38. In JavaScript, how do you compare two objects to see if they are equal ?

    Comparisons of objects are usually based on their references, not their properties. It is possible to check the equality of two objects by manually comparing their properties.

    //Strict property comparison
    function areObjectsEqual(obj1, obj2) {
      if (Object.keys(obj1).length !== Object.keys(obj2).length) {
        return false;
      }
    
      for (let key in obj1) {
        if (obj1[key] !== obj2[key]) {
          return false;
        }
      }
    
      return true;
    }
    
    const obj1 = { prop1: 'value1', prop2: 'value2' };
    const obj2 = { prop1: 'value1', prop2: 'value2' };
    
    console.log(areObjectsEqual(obj1, obj2)); // true
    
    
    //JSON serialization:
    function areObjectsEqual(obj1, obj2) {
      const str1 = JSON.stringify(obj1);
      const str2 = JSON.stringify(obj2);
      return str1 === str2;
    }
    
    const obj1 = { prop1: 'value1', prop2: 'value2' };
    const obj2 = { prop1: 'value1', prop2: 'value2' };
    
    console.log(areObjectsEqual(obj1, obj2)); // true
    
    
    //Library functions
    const obj1 = { prop1: 'value1', prop2: 'value2' };
    const obj2 = { prop1: 'value1', prop2: 'value2' };
    
    console.log(_.isEqual(obj1, obj2)); // true (using Lodash)
    console.log(R.equals(obj1, obj2)); // true (using Ramda)  

    39. In JavaScript, what is the Promise object used for ?

    Promises represent the completion or failure of asynchronous operations and are used to chain callbacks and catch errors.

    const fetchData = new Promise((resolve, reject) => {
      // Simulating an asynchronous operation (e.g., fetching data from a server)
      setTimeout(() => {
        const data = 'Some fetched data';
        if (data) {
          resolve(data); // Operation succeeded
        } else {
          reject('Data not found'); // Operation failed
        }
      }, 2000);
    });
    
    // Consuming the promise
    fetchData
      .then((result) => {
        console.log('Data:', result);
      })
      .catch((error) => {
        console.log('Error:', error);
      }); 

    40. In JavaScript, what is the difference between shallow and deep copies ?

    In shallow copies, properties of the original object are referenced, while in deep copies, the original object is completely duplicated.

    //Shallow Copy
    let dev1 = {name:'Vishal'}
    
    let dev2 = dev1; //Shallow Copy
    console.log(dev1); //{ name: 'Vishal' }
    dev2.name = 'Torgal'
    
    console.log(dev1); //{ name: 'Torgal' }
    console.log(dev2); //{ name: 'Torgal' }
    
    //Deep Copy
    let dev1 = {name:'Vishal'}
    
    let dev2 = JSON.parse(JSON.stringify(dev1)); //Deep Copy
    console.log(dev1); //{ name: 'Vishal' }
    dev2.name = 'Torgal'
    
    console.log(dev1); //{ name: 'Vishal' }
    console.log(dev2); //{ name: 'Torgal' }  

    41. How can a JavaScript callback-based function be converted into a promise-based function ?

    Promise constructors can be used to wrap a callback-based function in a promise. The promise can then be resolved or rejected based on the result of the callback.

    // Callback-based function
    function fetchData(callback) {
      // Simulating an asynchronous operation
      setTimeout(() => {
        const data = 'Some data';
        if (data) {
          callback(null, data); // Call the callback with the result
        } else {
          callback('Error: Data not found', null); // Call the callback with an error
        }
      }, 2000);
    }
    
    // Promise-based function
    function fetchDataPromise() {
      return new Promise((resolve, reject) => {
        // Invoke the original function inside the Promise executor
        fetchData((error, data) => {
          if (error) {
            reject(error); // Call reject with the error
          } else {
            resolve(data); // Call resolve with the result
          }
        });
      });
    }
    
    // Usage of the promise-based function
    fetchDataPromise()
      .then((data) => {
        console.log('Data:', data);
      })
      .catch((error) => {
        console.error('Error:', error);
      }); 

    42. In JavaScript, what is event-driven programming ?

    An event-driven program is one that follows the flow of events occurring in the program, such as user actions or system events.

    // HTML:
    // <button id="myButton">Click me!</button>
    
    // JavaScript:
    const button = document.getElementById('myButton');
    
    // Event Listener registration
    button.addEventListener('click', function(event) {
      console.log('Button clicked!');
    });
    
    console.log('Waiting for button click...');
    
    // The program continues to execute while waiting for events 

    43. What is the best way to detect the browsers user agent in JavaScript ?

    Navigator.userAgent gives you access to the user agent string for the browser.

    const userAgent = navigator.userAgent;
    console.log(userAgent); 

    44. How does JavaScripts fetch() function work ?

    You can use the fetch() function to make HTTP requests and asynchronously retrieve resources.

    fetch('https://api.example.com/data')
    .then(response => {
      if (!response.ok) {
        throw new Error('Network response was not OK');
      }
      return response.json(); // Parse the response body as JSON
    })
    .then(data => {
      console.log('Data:', data);
    })
    .catch(error => {
      console.error('Error:', error);
    }); 

    45. In JavaScript, how can you sort an array of objects based on a property value ?

    To sort an array of objects based on a specific property value, you can use the sort() method with a custom comparison function.

    const people = [
      { name: 'John', age: 25 },
      { name: 'Alice', age: 30 },
      { name: 'Bob', age: 20 }
    ];
    
    // Sorting the array based on the 'age' property in ascending order
    people.sort((a, b) => a.age - b.age);
    
    console.log(people);
    
    //Output
    [
      { name: 'Bob', age: 20 },
      { name: 'John', age: 25 },
      { name: 'Alice', age: 30 }
    ] 

    46. How does JavaScripts Object.keys() method work ?

    In the Object.keys() method, enumerable property names are returned in an array.

    const person = {
      name: 'John',
      age: 25,
      occupation: 'Engineer'
    };
    
    const keys = Object.keys(person);
    
    console.log(keys); //[ 'name', 'age', 'occupation' ] 

    47. In JavaScript, how do you convert a string to uppercase or lowercase ?

    A string can be converted to uppercase or lowercase using the toUpperCase() and toLowerCase() methods.

    const myString = 'Hello, World!';
    
    const uppercaseString = myString.toUpperCase();
    console.log(uppercaseString); // Output: "HELLO, WORLD!"
    
    const lowercaseString = myString.toLowerCase();
    console.log(lowercaseString); // Output: "hello, world!"  

    48. In JavaScript, what is a module ?

    A module contains related functions, variables, and classes within a self-contained unit of code. By using it, code can be better organized, reusable, and pollution of global namespaces can be avoided.

    // File: mathUtils.js (module)
    
    export function add(a, b) {
      return a + b;
    }
    
    export function subtract(a, b) {
      return a - b;
    }
    
    // File: main.js (usage)
    
    import { add, subtract } from './mathUtils.js';
    
    console.log(add(5, 3));       // Output: 8
    console.log(subtract(10, 4)); // Output: 6  

    49. What is the best way to handle asynchronous code in JavaScript ?

    When dealing with asynchronous code, you can use callbacks, promises, or the newer async/await syntax, which lets you handle nonblocking operations without blocking the main thread.

    //Using Callbacks
    function fetchData(callback) {
      // Simulating an asynchronous operation
      setTimeout(() => {
        const data = 'Some data';
        callback(null, data);
      }, 2000);
    }
    
    fetchData((error, data) => {
      if (error) {
        console.error('Error:', error);
      } else {
        console.log('Data:', data);
      }
    });
    
    
    //Using Promises
    function fetchData() {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          const data = 'Some data';
          resolve(data);
        }, 2000);
      });
    }
    
    fetchData()
      .then(data => {
        console.log('Data:', data);
      })
      .catch(error => {
        console.error('Error:', error);
      });
    
    
    //Using Async/await
    function fetchData() {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          const data = 'Some data';
          resolve(data);
        }, 2000);
      });
    }
    
    async function fetchDataAsync() {
      try {
        const data = await fetchData();
        console.log('Data:', data);
      } catch (error) {
        console.error('Error:', error);
      }
    }
    
    fetchDataAsync(); 

    50. what is event loop in javascript ?

    Event loops are used by JavaScript to handle asynchronous operations. The program runs in a single thread and is non-blocking. This guarantees that long-running operations are handled in a non-blocking manner, allowing the program to remain responsive while it waits for them to complete. Event loops continuously check the event queue for new tasks and execute them one by one.

    console.log('Start');
    
    // Asynchronous setTimeout function
    setTimeout(function() {
      console.log('Async task 1');
    }, 2000);
    
    // Synchronous task
    console.log('Sync task');
    
    // Asynchronous setTimeout function
    setTimeout(function() {
      console.log('Async task 2');
    }, 0);
    
    console.log('End');
    
    //Output
    Start
    Sync task
    End
    Async task 2
    Async task 1 

    51. what are webapi in javascript ?

    In JavaScript, web APIs refer to a set of APIs (Application Programming Interfaces) provided by web browsers. Through these APIs, JavaScript code interacts with the browser environment and performs various tasks.

    //***DOM API***
    
    // Get an element by its ID
    const element = document.getElementById('myElement');
    
    // Manipulate element content
    element.textContent = 'Hello, world!';
    
    // Add an event listener
    element.addEventListener('click', () => {
      console.log('Element clicked!');
    });
    
    
    //***Fetch API***
    
    fetch('https://api.com/data')
      .then(response => response.json())
      .then(data => {
        console.log(data);
      })
      .catch(error => {
        console.error(error);
      });
    
    
    //***localStorage API***
    
    // Store a value
    localStorage.setItem('username', 'John');
    
    // Retrieve a value
    const username = localStorage.getItem('username');
    console.log(username); // Output: John
    
    // Remove a value
    localStorage.removeItem('username');
    
    
    //***Geolocation API***
    
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(position => {
        const latitude = position.coords.latitude;
        const longitude = position.coords.longitude;
        console.log(latitude);
        console.log(longitude);
      }, error => {
        console.error(error);
      });
    } else {
      console.error('Geolocation is not supported by this browser.');
    }
    
    
    //***WebSockets API***
    
    const socket = new WebSocket('wss://example.com/socket');
    
    // Connection opened
    socket.addEventListener('open', event => {
      console.log('WebSocket connected.');
      socket.send('Hello Server!');
    });
    
    // Listen for messages
    socket.addEventListener('message', event => {
      console.log('Received message:', event.data);
    });
    
    // Connection closed
    socket.addEventListener('close', event => {
      console.log('WebSocket disconnected.');
    }); 

    52. Difference between argument and parameter ?

    Parameters are variables in function declarations. The placeholder represents the actual value that will be passed to the function.

    Whenever you call a function, you provide arguments. Each of these values is assigned to the parameters within the function.

    //Parameters
    function greet(name) {
      // "name" is the parameter here
      console.log("Hello, " + name);
    }
    
    // Arguments
    greet("Alice"); // "Alice" is the argument passed to the "name" parameter
    
    // Inside the function:
    console.log("Hello, Alice"); // This will print "Hello, Alice"

    53. What do you mean by dom manipulation ?

    Web development relies heavily on DOM manipulation, which allows developers to create dynamic and interactive web applications. In most cases, DOM manipulation through JavaScript involves adding new elements to a web page when a button is clicked or by submitting a form without reloading the page.

    54. Axios vs Fetch

    Axios Strengths

  • Automatic JSON Parsing
  • Built-in Error Handling
  • Cross-Browser Compatibility
  • Request Cancellation
  • Custom Interceptors
  • Progress Events
  • Axios Weaknesses

  • Third-party library Dependency
  • Potentially Larger Bundle Size
  • Fetch Strengths

  • Built-in Web API
  • Minimalist Design
  • Promise-Based
  • Fetch Weaknesses

  • No Error Handling
  • No JSON Parsing
  • No Interceptors
  • No Progress Tracking
  • 55. First-order function / First-class function

    Basically, it is a function that can be treated like any other data type

    First-order functions include:

  • Passed as an argument to other functions.
  • Returned as a value from other functions.
  • Assigned to variables.
  • Stored in data structures.
  • // Example of a first-order function
    function greet(name) {
        return "Hello, " + name + "!";
    }
    
    // Passing a function as an argument
    function sayHello(greetingFunction, name) {
        return greetingFunction(name);
    }
    
    console.log(sayHello(greet, "John")); // Output: "Hello, John!"
    
    // Returning a function from another function
    function createMultiplier(factor) {
        return function(x) {
            return x * factor;
        };
    }
    
    const double = createMultiplier(2);
    console.log(double(5)); // Output: 10

    56. Traditional functions vs Arrow functions

  • Normal functions: In situations where you need to control this binding completely, require the arguments object, or need to use the function as a constructor, you should use normal functions.
  • Arrow functions: In situations where you don't need the arguments object or you won't be using new, you should use arrow functions.
  • //Normal function
    function add(a, b) {
      return a + b;
    }
    
    //Arrow function
    const add = (a, b) => {
      return a + b;
    };
    // Or, for a single-expression body:
    const add = (a, b) => a + b;

    57. Arguments objects

    In JavaScript, an arguments object is an array-like object that holds all the arguments passed to a function. In this way, even when the function is defined without named parameters, it is possible to access the arguments dynamically within it.

    function example() {
      console.log(arguments.length); // Output: number of arguments passed to the function
      console.log(arguments[0]); // Output: value of the first argument
      console.log(arguments[1]); // Output: value of the second argument
      // and so on...
    }
    
    example(1, 'hello', true); 
    
    // Outputs
    3
    1
    hello

    58. Controlled Components vs Uncontrolled Components

    Controlled Components

  • Controlled components do not maintain their own states. Rather, the parent component passes down data and callbacks using props.
  • Controlled components are fully controlled by their parents.
  • User inputs and state changes are communicated to the parent component via callbacks, which update the parent component's own state.
  • Uncontrolled Components

  • Uncontrolled components, on the other hand, maintain their own internal states.
  • In contrast to parent components, they directly interact with the DOM to manage their state.
  • When to Use Which ?

    Use controlled components

  • It is used for complex forms that require validation, conditional rendering, or frequent updates.
  • When tight control of form data is essential.
  • Use uncontrolled components

  • In cases where complex interactions and validation are not needed. Optimizing performance and minimizing code are top priorities.
  • 59. Static type checking

    TypeScript: Errors can be caught by TypeScript before a code is executed, providing an additional layer of safety and preventing runtime errors. The type annotation allows you to specify types for variables, functions, and other elements of your code, and TypeScript will perform checks during compilation to ensure type safety.

    function add(a: number, b: number): number {
      return a + b;
    }
    
    // This will cause an error because "name" is a string, not a number
    const result = add(10, "hello");

    Flow: Flow is a JavaScript static type checker. There is a separate library you can add to your project. As part of the flow analysis, Flow inserts type annotation checks before executing your code.

    // @flow
    function add(a: number, b: number): number {
      return a + b;
    }
    
    // This will cause an error because "name" is a string, not a number
    const result = add(10, "hello");