FrontendDeveloper.in

JavaScript Interview Questions

  • Question 346

    What is the difference between Shallow and Deep copy

    There are two ways to copy an object,

    Shallow Copy: Shallow copy is a bitwise copy of an object. A new object is created that has an exact copy of the values in the original object. If any of the fields of the object are references to other objects, just the reference addresses are copied i.e., only the memory address is copied.

    Example

    var empDetails = {
    name: "John",
    age: 25,
    expertise: "Software Developer",
    };
    

    to create a duplicate

    var empDetailsShallowCopy = empDetails; //Shallow copying!
    

    if we change some property value in the duplicate one like this:

    empDetailsShallowCopy.name = "Johnson";
    

    The above statement will also change the name of empDetails, since we have a shallow copy. That means we're losing the original data as well.

    Deep copy: A deep copy copies all fields, and makes copies of dynamically allocated memory pointed to by the fields. A deep copy occurs when an object is copied along with the objects to which it refers.

    Example

    var empDetails = {
    name: "John",
    age: 25,
    expertise: "Software Developer",
    };
    

    Create a deep copy by using the properties from the original object into new variable

    var empDetailsDeepCopy = {
    name: empDetails.name,
    age: empDetails.age,
    expertise: empDetails.expertise,
    };
    

    Now if you change empDetailsDeepCopy.name, it will only affect empDetailsDeepCopy & not empDetails

  • Question 347

    How do you create specific number of copies of a string

    The repeat() method is used to construct and return a new string which contains the specified number of copies of the string on which it was called, concatenated together. Remember that this method has been added to the ECMAScript 2015 specification. Let's take an example of Hello string to repeat it 4 times,

    "Hello".repeat(4); // 'HelloHelloHelloHello'
    
  • Question 348

    How do you return all matching strings against a regular expression

    The matchAll() method can be used to return an iterator of all results matching a string against a regular expression. For example, the below example returns an array of matching string results against a regular expression,

    let regexp = /Hello(\d?)/g;
    let greeting = "Hello1Hello2Hello3";
    
    let greetingList = [...greeting.matchAll(regexp)];
    
    console.log(greetingList[0][0]); //Hello1
    console.log(greetingList[1][0]); //Hello2
    console.log(greetingList[2][0]); //Hello3
    
  • Question 349

    How do you trim a string at the beginning or ending

    The trim method of string prototype is used to trim on both sides of a string. But if you want to trim especially at the beginning or ending of the string then you can use trimStart/trimLeft and trimEnd/trimRight methods. Let's see an example of these methods on a greeting message,

    var greeting = "   Hello, Goodmorning!   ";
    
    console.log(greeting); // "   Hello, Goodmorning!   "
    console.log(greeting.trimStart()); // "Hello, Goodmorning!   "
    console.log(greeting.trimLeft()); // "Hello, Goodmorning!   "
    
    console.log(greeting.trimEnd()); // "   Hello, Goodmorning!"
    console.log(greeting.trimRight()); // "   Hello, Goodmorning!"
    
  • Question 350

    What is the output of below console statement with unary operator

    Let's take console statement with unary operator as given below,

    console.log(+"Hello"); // NaN
    

    The output of the above console log statement returns NaN. Because the element is prefixed by the unary operator and the JavaScript interpreter will try to convert that element into a number type. Since the conversion fails, the value of the statement results in NaN value.

  • Question 351

    Does javascript uses mixins

    JavaScript does not have built-in support for mixins as a formal language feature. However, developers commonly implement mixins using various patterns to enable code reuse and composition.

    A mixin is a way to add reusable functionality from one or more objects into a class or another object, without using classical inheritance. It promotes object composition by combining behaviors or properties from different sources into a single destination.

  • Question 352

    Mixin Example using Object composition

    // Define a mixin
    const canEat = {
    eat() {
    console.log("Eating...");
    }
    };
    
    const canWalk = {
    walk() {
    console.log("Walking...");
    }
    };
    
    const canRead = {
    read() {
    console.log("Reading...");
    }
    };
    
    // Create a class
    class Person {
    constructor(name) {
    this.name = name;
    }
    }
    
    // Apply mixins
    Object.assign(Person.prototype, canEat, canWalk, canRead);
    
    // Use it
    const person = new Person("Sudheer");
    person.eat();  // Output: Eating...
    person.walk(); // Output: Walking...
    person.read(); // Output: Reading...
    
  • Question 353

    Benefits

    • Avoids deep inheritance hierarchies
    • Encourages composition over inheritance
    • Promotes reusable and modular code

    Modern JavaScript favors mixin alternatives like composition, delegation, higher-order functions, and class mixins to promote reusable and modular code. Libraries like Lodash offer utilities for object composition, while frameworks like Vue.js provide built-in mixin features to promote reusable and modular code.

  • Question 354

    What is a thunk function

    A thunk is just a function which delays the evaluation of the value. It doesn’t take any arguments but gives the value whenever you invoke the thunk. i.e, It is used not to execute now but it will be sometime in the future. Let's take a synchronous example,

    const add = (x, y) => x + y;
    
    const thunk = () => add(2, 3);
    
    thunk(); // 5
    
  • Question 355

    What are asynchronous thunks

    The asynchronous thunks are useful to make network requests. Let's see an example of network requests,

    function fetchData(fn) {
    fetch("https://jsonplaceholder.typicode.com/todos/1")
    .then((response) => response.json())
    .then((json) => fn(json));
    }
    
    const asyncThunk = function () {
    return fetchData(function getData(data) {
    console.log(data);
    });
    };
    
    asyncThunk();
    

    The getData function won't be called immediately but it will be invoked only when the data is available from API endpoint. The setTimeout function is also used to make our code asynchronous. The best real time example is redux state management library which uses the asynchronous thunks to delay the actions to dispatch.

  • Question 356

    What is the output of below function calls

    Code snippet:

    const circle = {
    radius: 20,
    diameter() {
    return this.radius * 2;
    },
    perimeter: () => 2 * Math.PI * this?.radius,
    };
    
    console.log(circle.diameter());
    console.log(circle.perimeter());
    

    Output:

    The output is 40 and NaN. Remember that diameter is a regular function, whereas the value of perimeter is an arrow function. The this keyword of a regular function(i.e, diameter) refers to the surrounding scope which is a class(i.e, Shape object). Whereas this keyword of perimeter function refers to the surrounding scope which is a window object. Since there is no radius property on window objects it returns an undefined value and the multiple of number value returns NaN value.

  • Question 357

    How to remove all line breaks from a string

    The easiest approach is using regular expressions to detect and replace newlines in the string. In this case, we use replace function along with string to replace with, which in our case is an empty string.

    function remove_linebreaks( var message ) {
    return message.replace( /[\r\n]+/gm, "" );
    }
    

    In the above expression, g and m are for global and multiline flags.

  • Question 358

    What is the difference between reflow and repaint

    A repaint occurs when changes are made which affect the visibility of an element, but not its layout. Examples of this include outline, visibility, or background color. A reflow involves changes that affect the layout of a portion of the page (or the whole page). Resizing the browser window, changing the font, content changing (such as user typing text), using JavaScript methods involving computed styles, adding or removing elements from the DOM, and changing an element's classes are a few of the things that can trigger reflow. Reflow of an element causes the subsequent reflow of all child and ancestor elements as well as any elements following it in the DOM.

  • Question 359

    What happens with negating an array

    Negating an array with ! character will coerce the array into a boolean. Since Arrays are considered to be truthy So negating it will return false.

    console.log(![]); // false
    
  • Question 360

    What happens if we add two arrays

    If you add two arrays together, it will convert them both to strings and concatenate them. For example, the result of adding arrays would be as below,

    console.log(["a"] + ["b"]); // "ab"
    console.log([] + []); // ""
    console.log(![] + []); // "false", because ![] returns false.
    
Get LinkedIn Premium at Rs 399