FrontendDeveloper.in

JavaScript Interview Questions

  • Question 421

    What are the differences between for...of and for...in statements

    Both for...in and for...of statements iterate over js data structures. The only difference is over what they iterate:

    1. for..in iterates over all enumerable property keys of an object
    2. for..of iterates over the values of an iterable object.

    Let's explain this difference with an example,

    let arr = ["a", "b", "c"];
    
    arr.newProp = "newVlue";
    
    // key are the property keys
    for (let key in arr) {
    console.log(key); // 0, 1, 2 & newProp
    }
    
    // value are the property values
    for (let value of arr) {
    console.log(value); // a, b, c
    }
    

    Since for..in loop iterates over the keys of the object, the first loop logs 0, 1, 2 and newProp while iterating over the array object. The for..of loop iterates over the values of a arr data structure and logs a, b, c in the console.

  • Question 422

    How do you define instance and non-instance properties

    The Instance properties must be defined inside of class methods. For example, name and age properties defined inside constructor as below,

    class Person {
    constructor(name, age) {
    this.name = name;
    this.age = age;
    }
    }
    

    But Static(class) and prototype data properties must be defined outside of the ClassBody declaration. Let's assign the age value for Person class as below,

    Person.staticAge = 30;
    Person.prototype.prototypeAge = 40;
    
  • Question 423

    What is the difference between isNaN and Number.isNaN?

    1. isNaN: The global function isNaN converts the argument to a Number and returns true if the resulting value is NaN.
    2. Number.isNaN: This method does not convert the argument. But it returns true when the type is a Number and value is NaN.

    Let's see the difference with an example,

    isNaN(‘hello’);   // true
    Number.isNaN('hello'); // false
    
  • Question 424

    How to invoke an IIFE without any extra brackets?

    Immediately Invoked Function Expressions(IIFE) requires a pair of parenthesis to wrap the function which contains set of statements.

    (function (dt) {
    console.log(dt.toLocaleTimeString());
    })(new Date());
    

    Since both IIFE and void operator discard the result of an expression, you can avoid the extra brackets using void operator for IIFE as below,

    void (function (dt) {
    console.log(dt.toLocaleTimeString());
    })(new Date());
    
  • Question 425

    Is that possible to use expressions in switch cases?

    You might have seen expressions used in switch condition but it is also possible to use for switch cases by assigning true value for the switch condition. Let's see the weather condition based on temperature as an example,

    const weather = (function getWeather(temp) {
    switch (true) {
    case temp < 0:
    return "freezing";
    case temp < 10:
    return "cold";
    case temp < 24:
    return "cool";
    default:
    return "unknown";
    }
    })(10);
    
  • Question 427

    How do style the console output using CSS?

    You can add CSS styling to the console output using the CSS format content specifier %c. The console string message can be appended after the specifier and CSS style in another argument. Let's print the red color text using console.log and CSS specifier as below,

    console.log("%cThis is a red text", "color:red");
    

    It is also possible to add more styles for the content. For example, the font-size can be modified for the above text

    console.log(
    "%cThis is a red text with bigger font",
    "color:red; font-size:20px"
    );
    
  • Question 428

    What is nullish coalescing operator (??)?

    It is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand. This can be contrasted with the logical OR (||) operator, which returns the right-hand side operand if the left operand is any falsy value, not only null or undefined.

    console.log(null ?? true); // true
    console.log(false ?? true); // false
    console.log(undefined ?? true); // true
    
  • Question 429

    How do you group and nest console output?

    The console.group() can be used to group related log messages to be able to easily read the logs and use console.groupEnd()to close the group. Along with this, you can also nest groups which allows to output message in hierarchical manner.

    For example, if you’re logging a user’s details:

    console.group("User Details");
    console.log("name: Sudheer Jonna");
    console.log("job: Software Developer");
    
    // Nested Group
    console.group("Address");
    console.log("Street: Commonwealth");
    console.log("City: Los Angeles");
    console.log("State: California");
    
    // Close nested group
    console.groupEnd();
    
    // Close outer group
    console.groupEnd();
    

    You can also use console.groupCollapsed() instead of console.group() if you want the groups to be collapsed by default.

  • Question 430

    What is the difference between dense and sparse arrays?

    An array contains items at each index starting from first(0) to last(array.length - 1) is called as Dense array. Whereas if at least one item is missing at any index, the array is called as sparse.

    Let's see the below two kind of arrays,

    const avengers = ["Ironman", "Hulk", "CaptainAmerica"];
    console.log(avengers[0]); // 'Ironman'
    console.log(avengers[1]); // 'Hulk'
    console.log(avengers[2]); // 'CaptainAmerica'
    console.log(avengers.length); // 3
    
    const justiceLeague = ["Superman", "Aquaman", , "Batman"];
    console.log(justiceLeague[0]); // 'Superman'
    console.log(justiceLeague[1]); // 'Aquaman'
    console.log(justiceLeague[2]); // undefined
    console.log(justiceLeague[3]); // 'Batman'
    console.log(justiceLeague.length); // 4
    
  • Question 431

    What are the different ways to create sparse arrays?

    There are 4 different ways to create sparse arrays in JavaScript

    1. Array literal: Omit a value when using the array literal
    const justiceLeague = ["Superman", "Aquaman", , "Batman"];
    console.log(justiceLeague); // ['Superman', 'Aquaman', empty ,'Batman']
    
    1. Array() constructor: Invoking Array(length) or new Array(length)
    const array = Array(3);
    console.log(array); // [empty, empty ,empty]
    
    1. Delete operator: Using delete array[index] operator on the array
    const justiceLeague = ["Superman", "Aquaman", "Batman"];
    delete justiceLeague[1];
    console.log(justiceLeague); // ['Superman', empty, ,'Batman']
    
    1. Increase length property: Increasing length property of an array
    const justiceLeague = ["Superman", "Aquaman", "Batman"];
    justiceLeague.length = 5;
    console.log(justiceLeague); // ['Superman', 'Aquaman', 'Batman', empty, empty]
    
  • Question 432

    What is the difference between setTimeout, setImmediate and process.nextTick?

    1. Set Timeout: setTimeout() is to schedule execution of a one-time callback after delay milliseconds.
    2. Set Immediate: The setImmediate function is used to execute a function right after the current event loop finishes.
    3. Process NextTick: If process.nextTick() is called in a given phase, all the callbacks passed to process.nextTick() will be resolved before the event loop continues. This will block the event loop and create I/O Starvation if process.nextTick() is called recursively.
  • Question 433

    How do you reverse an array without modifying original array?

    The reverse() method reverses the order of the elements in an array but it mutates the original array. Let's take a simple example to demonistrate this case,

    const originalArray = [1, 2, 3, 4, 5];
    const newArray = originalArray.reverse();
    
    console.log(newArray); // [ 5, 4, 3, 2, 1]
    console.log(originalArray); // [ 5, 4, 3, 2, 1]
    

    There are few solutions that won't mutate the original array. Let's take a look.

    1. Using slice and reverse methods: In this case, just invoke the slice() method on the array to create a shallow copy followed by reverse() method call on the copy.
    const originalArray = [1, 2, 3, 4, 5];
    const newArray = originalArray.slice().reverse(); //Slice an array gives a new copy
    
    console.log(originalArray); // [1, 2, 3, 4, 5]
    console.log(newArray); // [ 5, 4, 3, 2, 1]
    
    1. Using spread and reverse methods: In this case, let's use the spread syntax (...) to create a copy of the array followed by reverse() method call on the copy.
    const originalArray = [1, 2, 3, 4, 5];
    const newArray = [...originalArray].reverse();
    
    console.log(originalArray); // [1, 2, 3, 4, 5]
    console.log(newArray); // [ 5, 4, 3, 2, 1]
    
    1. Using reduce and spread methods: Here execute a reducer function on an array elements and append the accumulated array on right side using spread syntax
    const originalArray = [1, 2, 3, 4, 5];
    const newArray = originalArray.reduce((accumulator, value) => {
    return [value, ...accumulator];
    }, []);
    
    console.log(originalArray); // [1, 2, 3, 4, 5]
    console.log(newArray); // [ 5, 4, 3, 2, 1]
    
    1. Using reduceRight and spread methods: Here execute a right reducer function(i.e. opposite direction of reduce method) on an array elements and append the accumulated array on left side using spread syntax
    const originalArray = [1, 2, 3, 4, 5];
    const newArray = originalArray.reduceRight((accumulator, value) => {
    return [...accumulator, value];
    }, []);
    
    console.log(originalArray); // [1, 2, 3, 4, 5]
    console.log(newArray); // [ 5, 4, 3, 2, 1]
    
    1. Using reduceRight and push methods: Here execute a right reducer function(i.e. opposite direction of reduce method) on an array elements and push the iterated value to the accumulator
    const originalArray = [1, 2, 3, 4, 5];
    const newArray = originalArray.reduceRight((accumulator, value) => {
    accumulator.push(value);
    return accumulator;
    }, []);
    
    console.log(originalArray); // [1, 2, 3, 4, 5]
    console.log(newArray); // [ 5, 4, 3, 2, 1]
    
  • Question 434

    How do you create custom HTML element?

    The creation of custom HTML elements involves two main steps,

    1. Define your custom HTML element: First you need to define some custom class by extending HTMLElement class. After that define your component properties (styles,text etc) using connectedCallback method. Note: The browser exposes a function called customElements.define inorder to reuse the element.
    class CustomElement extends HTMLElement {
    connectedCallback() {
    this.innerHTML = "This is a custom element";
    }
    }
    customElements.define("custom-element", CustomElement);
    
    1. Use custom element just like other HTML element: Declare your custom element as a HTML tag.
    <body>
    <custom-element>
    </body>
    
  • Question 435

    What is global execution context?

    The global execution context is the default or first execution context that is created by the JavaScript engine before any code is executed(i.e, when the file first loads in the browser). All the global code that is not inside a function or object will be executed inside this global execution context. Since JS engine is single threaded there will be only one global environment and there will be only one global execution context.

    For example, the below code other than code inside any function or object is executed inside the global execution context.

    var x = 10;
    
    function A() {
    console.log("Start function A");
    
    function B() {
    console.log("In function B");
    }
    
    B();
    }
    
    A();
    
    console.log("GlobalContext");
    
Get LinkedIn Premium at Rs 399