FrontendDeveloper.in

JavaScript Interview Questions

  • Question 301

    How to set the cursor to wait

    The cursor can be set to wait in JavaScript by using the property cursor. Let's perform this behavior on page load using the below function.

    function myFunction() {
    window.document.body.style.cursor = "wait";
    }
    

    and this function invoked on page load

    <body onload="myFunction()"></body>
    
  • Question 302

    How do you create an infinite loop

    You can create infinite loops using for and while loops without using any expressions. The for loop construct or syntax is better approach in terms of ESLint and code optimizer tools,

    for (;;) {}
    while (true) {}
    
  • Question 303

    Why do you need to avoid with statement

    JavaScript's with statement was intended to provide a shorthand for writing recurring accesses to objects. So it can help reduce file size by reducing the need to repeat a lengthy object reference without performance penalty. Let's take an example where it is used to avoid redundancy when accessing an object several times.

    a.b.c.greeting = "welcome";
    a.b.c.age = 32;
    

    Using with it turns this into:

    with (a.b.c) {
    greeting = "welcome";
    age = 32;
    }
    

    But this with statement creates performance problems since one cannot predict whether an argument will refer to a real variable or to a property inside the with argument.

  • Question 304

    What is the output of the following for loops

    for (var i = 0; i < 4; i++) {
    // global scope
    setTimeout(() => console.log(i));
    }
    
    for (let i = 0; i < 4; i++) {
    // block scope
    setTimeout(() => console.log(i));
    }
    

    The output of the above for loops is 4 4 4 4 and 0 1 2 3

    Explanation: Due to the event queue/loop of javascript, the setTimeout callback function is called after the loop has been executed. Since the variable i is declared with the var keyword it became a global variable and the value was equal to 4 using iteration when the time setTimeout function is invoked. Hence, the output of the second loop is 4 4 4 4.

    Whereas in the second loop, the variable i is declared as the let keyword it becomes a block scoped variable and it holds a new value(0, 1 ,2 3) for each iteration. Hence, the output of the first loop is 0 1 2 3.

  • Question 305

    List down some of the features of ES6

    Below are the list of some new features of ES6,

    1. Support for constants or immutable variables
    2. Block-scope support for variables, constants and functions
    3. Arrow functions
    4. Default parameters
    5. Rest and Spread Parameters
    6. Template Literals
    7. Multi-line Strings
    8. Destructuring Assignment
    9. Enhanced Object Literals
    10. Promises
    11. Classes
    12. Modules
  • Question 306

    What is ES6

    ES6 is the sixth edition of the javascript language and it was released in June 2015. It was initially known as ECMAScript 6 (ES6) and later renamed to ECMAScript 2015. Almost all the modern browsers support ES6 but for the old browsers there are many transpilers, like Babel.js etc.

  • Question 307

    Can I redeclare let and const variables

    No, you cannot redeclare let and const variables. If you do, it throws below error

    Uncaught SyntaxError: Identifier 'someVariable' has already been declared
    

    Explanation: The variable declaration with var keyword refers to a function scope and the variable is treated as if it were declared at the top of the enclosing scope due to hoisting feature. So all the multiple declarations contributing to the same hoisted variable without any error. Let's take an example of re-declaring variables in the same scope for both var and let/const variables.

    var name = "John";
    function myFunc() {
    var name = "Nick";
    var name = "Abraham"; // Re-assigned in the same function block
    alert(name); // Abraham
    }
    myFunc();
    alert(name); // John
    

    The block-scoped multi-declaration throws syntax error,

    let name = "John";
    function myFunc() {
    let name = "Nick";
    let name = "Abraham"; // Uncaught SyntaxError: Identifier 'name' has already been declared
    alert(name);
    }
    
    myFunc();
    alert(name);
    
  • Question 308

    Does the `const` variable make the value immutable

    No, the const variable doesn't make the value immutable. But it disallows subsequent assignments(i.e, You can declare with assignment but can't assign another value later)

    const userList = [];
    userList.push("John"); // Can mutate even though it can't re-assign
    console.log(userList); // ['John']
    
  • Question 309

    What are default parameters

    In ES5, we need to depend on logical OR operators to handle default values of function parameters. Whereas in ES6, Default function parameters feature allows parameters to be initialized with default values if no value or undefined is passed. Let's compare the behavior with an examples,

    //ES5
    var calculateArea = function (height, width) {
    height = height || 50;
    width = width || 60;
    
    return width * height;
    };
    console.log(calculateArea()); //300
    

    The default parameters makes the initialization more simpler,

    //ES6
    var calculateArea = function (height = 50, width = 60) {
    return width * height;
    };
    
    console.log(calculateArea()); //300
    
  • Question 310

    What are template literals

    Template literals or template strings are string literals allowing embedded expressions. These are enclosed by the back-tick (`) character instead of double or single quotes. In ES6, this feature enables using dynamic expressions as below,

    var greeting = `Welcome to JS World, Mr. ${firstName} ${lastName}.`;
    

    In ES5, you need break string like below,

    var greeting = 'Welcome to JS World, Mr. ' + firstName + ' ' + lastName.`
    

    Note: You can use multi-line strings and string interpolation features with template literals.

  • Question 311

    How do you write multi-line strings in template literals

    In ES5, you would have to use newline escape characters('\n') and concatenation symbols(+) in order to get multi-line strings.

    console.log("This is string sentence 1\n" + "This is string sentence 2");
    

    Whereas in ES6, You don't need to mention any newline sequence character,

    console.log(`This is string sentence
    'This is string sentence 2`);
    
  • Question 312

    What are nesting templates

    The nesting template is a feature supported within template literals syntax to allow inner backticks inside a placeholder ${ } within the template. For example, the below nesting template is used to display the icons based on user permissions whereas outer template checks for platform type,

    const iconStyles = `icon ${
    isMobilePlatform()
    ? ""
    : `icon-${user.isAuthorized ? "submit" : "disabled"}`
    }`;
    

    You can write the above use case without nesting template features as well. However, the nesting template feature is more compact and readable.

    //Without nesting templates
    const iconStyles = `icon ${
    isMobilePlatform()
    ? ""
    : user.isAuthorized
    ? "icon-submit"
    : "icon-disabled"
    }`;
    
  • Question 313

    What are tagged templates

    Tagged templates are the advanced form of templates in which tags allow you to parse template literals with a function. The tag function accepts the first parameter as an array of strings and remaining parameters as expressions. This function can also return manipulated strings based on parameters. Let's see the usage of this tagged template behavior of an IT professional skill set in an organization,

    var user1 = "John";
    var skill1 = "JavaScript";
    var experience1 = 15;
    
    var user2 = "Kane";
    var skill2 = "JavaScript";
    var experience2 = 5;
    
    function myInfoTag(strings, userExp, experienceExp, skillExp) {
    var str0 = strings[0]; // "Mr/Ms. "
    var str1 = strings[1]; // " is a/an "
    var str2 = strings[2]; // "in"
    
    var expertiseStr;
    if (experienceExp > 10) {
    expertiseStr = "expert developer";
    } else if (skillExp > 5 && skillExp <= 10) {
    expertiseStr = "senior developer";
    } else {
    expertiseStr = "junior developer";
    }
    
    return `${str0}${userExp}${str1}${expertiseStr}${str2}${skillExp}`;
    }
    
    var output1 = myInfoTag`Mr/Ms. ${user1} is a/an ${experience1} in ${skill1}`;
    var output2 = myInfoTag`Mr/Ms. ${user2} is a/an ${experience2} in ${skill2}`;
    
    console.log(output1); // Mr/Ms. John is a/an expert developer in JavaScript
    console.log(output2); // Mr/Ms. Kane is a/an junior developer in JavaScript
    
  • Question 314

    What are raw strings

    ES6 provides a raw strings feature using the String.raw() method which is used to get the raw string form of template strings. This feature allows you to access the raw strings as they were entered, without processing escape sequences. For example, the usage would be as below,

    var calculationString = String.raw`The sum of numbers is \n${
    1 + 2 + 3 + 4
    }!`;
    console.log(calculationString); // The sum of numbers is \n10!
    

    If you don't use raw strings, the newline character sequence will be processed by displaying the output in multiple lines

    var calculationString = `The sum of numbers is \n${1 + 2 + 3 + 4}!`;
    console.log(calculationString);
    // The sum of numbers is
    // 10!
    

    Also, the raw property is available on the first argument to the tag function

    function tag(strings) {
    console.log(strings.raw[0]);
    }
    
  • Question 315

    What is destructuring assignment

    The destructuring assignment is a JavaScript expression that makes it possible to unpack values from arrays or properties from objects into distinct variables. Let's get the month values from an array using destructuring assignment

    var [one, two, three] = ["JAN", "FEB", "MARCH"];
    
    console.log(one); // "JAN"
    console.log(two); // "FEB"
    console.log(three); // "MARCH"
    

    and you can get user properties of an object using destructuring assignment,

    var { name, age } = { name: "John", age: 32 };
    
    console.log(name); // John
    console.log(age); // 32
    
Get LinkedIn Premium at Rs 399