FrontendDeveloper.in

JavaScript Interview Questions

  • Question 466

    What are the different ways to execute external scripts?

    There are three different ways to execute external scripts,

    1. async: The script is downloaded in parallel to parsing the page, and executed as soon as it is available even before parsing completes. The parsing of the page is going to be interuppted once the script is downloaded completely and then the script is executed. Thereafter, the parsing of the remaining page will continue.

    The syntax for async usage is as shown below,

    <script src="demo.js" async></script>
    
    1. defer: The script is downloaded in parallel to parsing the page, and executed after the page has finished parsing.

    The syntax for defer usage is as shown below,

    <script src="demo.js" defer></script>
    
    1. Neither async or defer: The script is downloaded and executed immediately by blocking parsing of the page until the script execution is completed.

    Note: You should only use either async or defer attribute if the src attribute is present.

  • Question 467

    What is Lexical Scope?

    Lexical scope is the ability for a function scope to access variables from the parent scope.

    <script>
    function x(){
    var a=10;
    function y(){
    console.log(a); // will print a , because of lexical scope, it will first look 'a' in
    //its local memory space and then in its parent functions memory space
    }
    y();
    }
    x();
    </script>
    
  • Question 468

    How to detect system dark mode in javascript?

    The combination of Window.matchMedia() utility method along with media query is used to check if the user has selected a dark color scheme in their operating system settings or not. The CSS media query prefers-color-scheme needs to be passed to identify system color theme.

    The following javascript code describes the usage,

    const hasDarkColorScheme = () =>
    window.matchMedia &&
    window.matchMedia("(prefers-color-scheme: dark)").matches;
    

    You can also watch changes to system color scheme using addEventListener,

    window
    .matchMedia("(prefers-color-scheme: dark)")
    .addEventListener("change", (event) => {
    const theme = event.matches ? "dark" : "light";
    });
    

    Note: The matchMedia method returns MediaQueryList object stores information from a media query.

  • Question 469

    What is the purpose of requestAnimationFrame method?

    The requestAnimationFrame() method in JavaScript is used to schedule a function to be called before the next repaint of the browser window, allowing you to create smooth, efficient animations. It's primarily used for animations and visual updates, making it an essential tool for improving performance when you're animating elements on the web.

    const element = document.getElementById("myElement");
    function animate() {
    let currentPosition = parseInt(window.getComputedStyle(element).left, 10);
    
    // Move the element 2px per frame
    currentPosition += 2;
    element.style.left = currentPosition + "px";
    // If the element hasn't moved off-screen, request the next frame
    if (currentPosition < window.innerWidth) {
    requestAnimationFrame(animate);
    }
    }
    // Start the animation
    requestAnimationFrame(animate);
    
  • Question 470

    What is the difference between substring and substr methods?

    Both substring and substr are used to extract parts of a string, but there are subtle differences between the substring() and substr() methods in terms of syntax and behavior.

    1. substring(start, end)
    • Parameters:
    • start: The index to start extracting (inclusive).
    • end: The index to stop extracting (exclusive).
    • Behavior:
    • If start > end, it swaps the arguments.
    • Negative values are treated as 0.
    let str = "Hello World";
    console.log(str.substring(0, 5));   // "Hello"
    console.log(str.substring(5, 0));   // "Hello" (swapped)
    console.log(str.substring(-3, 4));  // "Hell" (negative = 0)
    
    1. substr(start, length) (Deprecated)
    • Parameters:
    • start: The index to start extracting.
    • length: The number of characters to extract.
    • Behavior:
    • If start is negative, it counts from the end of the string.
    • If length is omitted, it extracts to the end of the string.
    let str = "Hello World"; console.log(str.substr(0, 5)); // "Hello"
    console.log(str.substr(-5, 3)); // "Wor" (starts from 'W')`
    

    Note: substr() is considered a legacy feature in ECMAScript, so it is best to avoid using it if possible.

  • Question 471

    How to find the number of parameters expected by a function?

    The function's object has a length property which tells you how many formal parameters expected by a function. This is a static value defined by the function, not the number of arguments the function is called with(arguments.length). The basic usage of length propery is,

    function multiply(x, y) {
    return x * y;
    }
    
    function sum(a, b, c) {
    return a + b + c;
    }
    
    console.log(multiply.length); //2
    console.log(sum.length); //3
    

    But there are few important rules which needs to be noted while using length property.

    1. Default values: Only the parameters which exists before a default value are considered.
    function sum(a, b = 2, c = 3) {
    return a + b + c;
    }
    console.log(sum.length); // 1
    
    1. Rest params: The rest parameters are excluded with in length property.
    function sum(a, b, ...moreArgs) {
    let total = a + b;
    for (const arg of moreArgs) {
    total += arg;
    }
    return total;
    }
    console.log(sum.length); // 2
    
    1. Destructuring patterns: Each destructuring pattern counted as a single parameter.
    function func([a, b], { x, y }) {
    console.log(a + b, x, y);
    }
    
    console.log(func.length); // 2
    

    Note: The Function constructor is itself a function object and it has a length property of 1.

  • Question 472

    What is globalThis, and what is the importance of it?

    Nowadays JavaScript language is used in a wide variety of environments and each environment has its own object model. Due to this fact, there are different ways(syntax) to access the global object.

    1. In web browser, the global object is accessible via window, self, or frames.
    2. In Node environment, you have to use global.
    3. In Web workers, the global object is available through self.

    The globalThis property provides a standard way of accessing the global object without writing various code snippet to support multiple environments. For example, the global object retuned from multiple environments as shown below,

    //1. browser environment
    console.log(globalThis); // => Window {...}
    
    //2. node.js environment
    console.log(globalThis); // => Object [global] {...}
    
    //3. web worker environment
    console.log(globalThis); // => DedicatedWorkerGlobalScope {...}
    
  • Question 473

    What are the array mutation methods?

    JavaScript array methods can be categorized into two groups:

    1. Mutating methods: These are the methods that directly modify the original array.
    2. Non-mutating methods: These methods return a new array without altering the original one.

    There are 9 methods in total that mutate the arrays,

    1. push: Adds one or more elements to the end of the array and returns the new length.
    2. pop: Removes the last element from the array and returns that element.
    3. unshift: Adds one or more elements to the beginning of the array and returns the new length..
    4. shift: Removes the first element from the array and returns that element.
    5. splice: Adds or removes elements from the array at a specific index position.
    6. sort: Sorts the elements of the array in-place based on a given sorting criteria.
    7. reverse: Reverses the order of elements in the given array.
    8. fill: Fills all elements of the array with a specific value.
    9. copyWithIn: Copies a sequence of elements within the array to a specified target index in the same array.
  • Question 474

    What is module scope in JavaScript?

    Module scope is a feature introduced with ES6 (ES2015) modules that creates a scope specific to a module file, isolating variables and functions declared within it from the global scope and other modules. Variables and functions declared in a module are private by default and can only be accessed by other modules if they are explicitly exported.

    Key characteristics of module scope:

    1. Variables declared in a module are scoped to that module only.
    2. Each module has its own top-level scope
    3. Variables and functions need to be explicitly exported to be used in other modules
    4. The global scope cannot access module variables unless they are explicitly exported and imported
    5. Modules are always executed in strict mode
    // moduleA.js
    
    // This variable is PRIVATE to moduleA. It's like a tool inside a closed box.
    const privateVariable = "I am private";
    
    // This variable is PUBLIC because it's exported. Others can use it when they import moduleA.
    export const publicVariable = "I am public";
    
    // PUBLIC function because it's exported. But it can still access privateVariable inside moduleA.
    export function publicFunction() {
    console.log(privateVariable); // ✅ This works because we're inside the same module.
    return "Hello from publicFunction!";
    }
    
    // moduleB.js
    
    // Importing PUBLIC items from moduleA.
    import { publicVariable, publicFunction } from "./moduleA.js";
    
    console.log(publicVariable); // ✅ "I am public" - Works because it's exported.
    console.log(publicFunction()); // ✅ "Hello from publicFunction!" - Works as well.
    
    // ❌ This will cause an ERROR because privateVariable was NOT exported from moduleA.
    // console.log(privateVariable);   // ❌ ReferenceError: privateVariable is not defined
    

    Common use cases and benefits:

    • Encapsulation of module-specific code
    • Prevention of global scope pollution
    • Better code organization and maintenance
    • Explicit dependency management
    • Protection of private implementation details
  • Question 475

    What are shadowing and illegal shadowing?

    Both shadowing and illegal shadowing refer to how variable names can "hide" or override others within nested scopes.

    Shadowing occurs when a variable declared within a certain scope (like a function or block) has the same name as a variable declared in an outer scope. The inner variable shadows the outer one — meaning, the inner variable takes precedence in its own scope.

    Let's take an example where the inner a inside func() shadows the outer variable a.

    let a = 10;
    
    function func() {
    let a = 20; // Shadows the outer 'a'
    console.log(a); // 20
    }
    
    func();
    console.log(a); // 10
    

    Illegal shadowing in JavaScript refers to a syntax error that happens when you try to declare a block-scoped variable (let or const) with the same name as a variable declared using var in the same or an overlapping scope.

    For example, if you declare both block-scoped variable and function scoped variable using the same name inside a function causes an illegal shadowing.

    function test() {
    var a = 10;
    let a = 20; // SyntaxError: Identifier 'a' has already been declared
    }
    

    As an another example, if you declare a variable with let or const in an outer scope, and then try to redeclare it with var inside a nested block, JavaScript throws an error — even though var is supposed to be function-scoped. Since the var appears in a block, it ends up trying to overwrite the let in the outer scope, which causes a conflict.

    let a = 10;
    {
    var a = 20; // SyntaxError: Identifier 'a' has already been declared
    console.log(a);
    }
    
  • Question 476

    Why is it important to remove event listeners after use?

    In JavaScript, you need to be mindful of removing event listeners to avoid memory leaks — especially in long-lived apps like single-page applications (SPAs) or when working with frameworks/libraries. Eventhough JavaScript has automatic garbage collection, memory leaks can still happen if:

    1. A DOM element is removed, but a listener still references it.
    2. A callback (event listener) holds a reference to a large object or closure that can't be cleaned up.
    3. Global objects like window, document etc retain listeners indefinitely unless manually removed.

    So if you add any event listeners to DOM element, it is a good practice to remove it after its usage as shown below,

    const button = document.getElementById("btn");
    
     function handleClick() {
    console.log("Clicked!");
     }
    
     button.addEventListener("click", handleClick);
    
     // Always remove when done
     button.removeEventListener("click", handleClick);
    
  • Question 477

    What is structuredClone and how is it used for deep copying objects?

    In JavaScript, structuredClone() is a built-in method used to create a deep copy of a value. It safely clones nested objects, arrays, Maps, Sets, Dates, TypedArrays, and even circular references — without sharing references to the original value. This prevents accidental mutations and makes it useful for state management and data processing.

    For example, the below snippet demonstrates deep cloning of a nested object,

    const originalObject = {
    name: "Deep Copy Test",
    nested: {
    value: 10,
    list: [1, 2, 3]
    },
    };
    
    const deepCopy = structuredClone(originalObject);
    
    // Modify cloned value
    deepCopy.nested.value = 99;
    deepCopy.nested.list.push(4);
    console.log(originalObject.nested.value); // 10
    console.log(deepCopy.nested.value);       // 99
    console.log(originalObject.nested.list);  // [1, 2, 3]
    console.log(deepCopy.nested.list);        // [1, 2, 3, 4]
    
  • Question 478

    What is the difference between const and Object.freeze

    The main difference is that const applies to variables (bindings), while Object.freeze() applies to values (objects).

    1. const: Prevents the reassignment of a variable identifier. It ensures that the variable name always points to the same memory reference. However, if the variable holds an object or array, the contents of that object can still be modified.
    2. Object.freeze(): Prevents the modification of an object's properties. It makes the object immutable (you cannot add, remove, or change properties), but it does not affect the variable assignment itself (unless the variable is also declared with const).

    Example:

    // Case 1: Using const (Reassignment prevented, Mutation allowed)
    const person = { name: "John" };
    person.name = "Doe"; // ✅ Allowed: The object is mutable
    console.log(person.name); // "Doe"
    
    // person = { name: "Jane" }; // ❌ Error: Assignment to constant variable
    
    // Case 2: Using Object.freeze (Reassignment allowed, Mutation prevented)
    let profile = { name: "John" };
    Object.freeze(profile);
    
    profile.name = "Doe"; // ❌ Ignored (or throws TypeError in strict mode)
    console.log(profile.name); // "John"
    
    profile = { name: "Jane" }; // ✅ Allowed: 'profile' is declared with 'let'
    console.log(profile.name); // "Jane"
    
  • Question 479

    Coding Exercise

    1. What is the output of below code

    var car = new Vehicle("Honda", "white", "2010", "UK");
    console.log(car);
    
    function Vehicle(model, color, year, country) {
    this.model = model;
    this.color = color;
    this.year = year;
    this.country = country;
    }
    
    • 1: Undefined
    • 2: ReferenceError
    • 3: null
    • 4: {model: "Honda", color: "white", year: "2010", country: "UK"}

    Answer

    Answer: 4

    The function declarations are hoisted similar to any variables. So the placement for Vehicle function declaration doesn't make any difference.


    2. What is the output of below code

    function foo() {
    let x = (y = 0);
    x++;
    y++;
    return x;
    }
    
    console.log(foo(), typeof x, typeof y);
    
    • 1: 1, undefined and undefined
    • 2: ReferenceError: X is not defined
    • 3: 1, undefined and number
    • 4: 1, number and number

    Answer

    Answer: 3

    Of course the return value of foo() is 1 due to the increment operator. But the statement let x = y = 0 declares a local variable x. Whereas y declared as a global variable accidentally. This statement is equivalent to,

    let x;
    window.y = 0;
    x = window.y;
    

    Since the block scoped variable x is undefined outside of the function, the type will be undefined too. Whereas the global variable y is available outside the function, the value is 0 and type is number.


    3. What is the output of below code

    function main() {
    console.log("A");
    setTimeout(function print() {
    console.log("B");
    }, 0);
    console.log("C");
    }
    main();
    
    • 1: A, B and C
    • 2: B, A and C
    • 3: A and C
    • 4: A, C and B

    Answer

    Answer: 4

    The statements order is based on the event loop mechanism. The order of statements follows the below order,

    1. At first, the main function is pushed to the stack.
    2. Then the browser pushes the first statement of the main function( i.e, A's console.log) to the stack, executing and popping out immediately.
    3. But setTimeout statement moved to Browser API to apply the delay for callback.
    4. In the meantime, C's console.log added to stack, executed and popped out.
    5. The callback of setTimeout moved from Browser API to message queue.
    6. The main function popped out from stack because there are no statements to execute
    7. The callback moved from message queue to the stack since the stack is empty.
    8. The console.log for B is added to the stack and display on the console.

    4. What is the output of below equality check

    console.log(0.1 + 0.2 === 0.3);
    
    • 1: false
    • 2: true

    Answer

    Answer: 1

    This is due to the float point math problem. Since the floating point numbers are encoded in binary format, the addition operations on them lead to rounding errors. Hence, the comparison of floating points doesn't give expected results. You can find more details about the explanation here 0.30000000000000004.com/


    5. What is the output of below code

    var y = 1;
    if (function f() {}) {
    y += typeof f;
    }
    console.log(y);
    
    • 1: 1function
    • 2: 1object
    • 3: ReferenceError
    • 4: 1undefined

    Answer

    Answer: 4

    The main points in the above code snippets are,

    1. You can see function expression instead function declaration inside if statement. So it always returns true.
    2. Since it is not declared(or assigned) anywhere, f is undefined and typeof f is undefined too.

    In other words, it is same as

    var y = 1;
    if ("foo") {
    y += typeof f;
    }
    console.log(y);
    

    Note: It returns 1object for MS Edge browser


    6. What is the output of below code

    function foo() {
    return;
    {
    message: "Hello World";
    }
    }
    console.log(foo());
    
    • 1: Hello World
    • 2: Object {message: "Hello World"}
    • 3: Undefined
    • 4: SyntaxError

    Answer

    Answer: 3

    This is a semicolon issue. Normally semicolons are optional in JavaScript. So if there are any statements(in this case, return) missing semicolon, it is automatically inserted immediately. Hence, the function returned as undefined.

    Whereas if the opening curly brace is along with the return keyword then the function is going to be returned as expected.

    function foo() {
    return {
    message: "Hello World",
    };
    }
    console.log(foo()); // {message: "Hello World"}
    

    7. What is the output of below code

    var myChars = ["a", "b", "c", "d"];
    delete myChars[0];
    console.log(myChars);
    console.log(myChars[0]);
    console.log(myChars.length);
    
    • 1: [empty, 'b', 'c', 'd'], empty, 3
    • 2: [null, 'b', 'c', 'd'], empty, 3
    • 3: [empty, 'b', 'c', 'd'], undefined, 4
    • 4: [null, 'b', 'c', 'd'], undefined, 4

    Answer

    Answer: 3

    The delete operator will delete the object property but it will not reindex the array or change its length. So the number or elements or length of the array won't be changed. If you try to print myChars then you can observe that it doesn't set an undefined value, rather the property is removed from the array. The newer versions of Chrome use empty instead of undefined to make the difference a bit clearer.


    8. What is the output of below code in latest Chrome

    var array1 = new Array(3);
    console.log(array1);
    
    var array2 = [];
    array2[2] = 100;
    console.log(array2);
    
    var array3 = [, , ,];
    console.log(array3);
    
    • 1: [undefined × 3], [undefined × 2, 100], [undefined × 3]
    • 2: [empty × 3], [empty × 2, 100], [empty × 3]
    • 3: [null × 3], [null × 2, 100], [null × 3]
    • 4: [], [100], []

    Answer

    Answer: 2

    The latest chrome versions display sparse array(they are filled with holes) using this empty x n notation. Whereas the older versions have undefined x n notation. Note: The latest version of FF displays n empty slots notation.


    9. What is the output of below code

    const obj = {
    prop1: function () {
    return 0;
    },
    prop2() {
    return 1;
    },
    ["prop" + 3]() {
    return 2;
    },
    };
    
    console.log(obj.prop1());
    console.log(obj.prop2());
    console.log(obj.prop3());
    
    • 1: 0, 1, 2
    • 2: 0, { return 1 }, 2
    • 3: 0, { return 1 }, { return 2 }
    • 4: 0, 1, undefined

    Answer

    Answer: 1

    ES6 provides method definitions and property shorthands for objects. So both prop2 and prop3 are treated as regular function values.


    10. What is the output of below code

    console.log(1 < 2 < 3);
    console.log(3 > 2 > 1);
    
    • 1: true, true
    • 2: true, false
    • 3: SyntaxError, SyntaxError,
    • 4: false, false

    Answer

    Answer: 2

    The important point is that if the statement contains the same operators(e.g, < or >) then it can be evaluated from left to right. The first statement follows the below order,

    1. console.log(1 < 2 < 3);
    2. console.log(true < 3);
    3. console.log(1 < 3); // True converted as 1 during comparison
    4. True

    Whereas the second statement follows the below order,

    1. console.log(3 > 2 > 1);
    2. console.log(true > 1);
    3. console.log(1 > 1); // False converted as 0 during comparison
    4. False

    11. What is the output of below code in non-strict mode

    function printNumbers(first, second, first) {
    console.log(first, second, first);
    }
    printNumbers(1, 2, 3);
    
    • 1: 1, 2, 3
    • 2: 3, 2, 3
    • 3: SyntaxError: Duplicate parameter name not allowed in this context
    • 4: 1, 2, 1

    Answer

    Answer: 2

    In non-strict mode, the regular JavaScript functions allow duplicate named parameters. The above code snippet has duplicate parameters on 1st and 3rd parameters. The value of the first parameter is mapped to the third argument which is passed to the function. Hence, the 3rd argument overrides the first parameter.

    Note: In strict mode, duplicate parameters will throw a Syntax Error.


    12. What is the output of below code

    const printNumbersArrow = (first, second, first) => {
    console.log(first, second, first);
    };
    printNumbersArrow(1, 2, 3);
    
    • 1: 1, 2, 3
    • 2: 3, 2, 3
    • 3: SyntaxError: Duplicate parameter name not allowed in this context
    • 4: 1, 2, 1

    Answer

    Answer: 3

    Unlike regular functions, the arrow functions doesn't not allow duplicate parameters in either strict or non-strict mode. So you can see SyntaxError in the console.


    13. What is the output of below code

    const arrowFunc = () => arguments.length;
    console.log(arrowFunc(1, 2, 3));
    
    • 1: ReferenceError: arguments is not defined
    • 2: 3
    • 3: undefined
    • 4: null

    Answer

    Answer: 1

    Arrow functions do not have an arguments, super, this, or new.target bindings. So any reference to arguments variable tries to resolve to a binding in a lexically enclosing environment. In this case, the arguments variable is not defined outside of the arrow function. Hence, you will receive a reference error.

    Where as the normal function provides the number of arguments passed to the function

    const func = function () {
    return arguments.length;
    };
    console.log(func(1, 2, 3));
    

    But If you still want to use an arrow function then rest operator on arguments provides the expected arguments

    const arrowFunc = (...args) => args.length;
    console.log(arrowFunc(1, 2, 3));
    

    14. What is the output of below code

    console.log(String.prototype.trimLeft.name === "trimLeft");
    console.log(String.prototype.trimLeft.name === "trimStart");
    
    • 1: True, False
    • 2: False, True

    Answer

    Answer: 2

    In order to be consistent with functions like String.prototype.padStart, the standard method name for trimming the whitespaces is considered as trimStart. Due to web web compatibility reasons, the old method name 'trimLeft' still acts as an alias for 'trimStart'. Hence, the prototype for 'trimLeft' is always 'trimStart'


    15. What is the output of below code

    console.log(Math.max());
    
    • 1: undefined
    • 2: Infinity
    • 3: 0
    • 4: -Infinity

    Answer

    Answer: 4

    -Infinity is the initial comparant because almost every other value is bigger. So when no arguments are provided, -Infinity is going to be returned. Note: Zero number of arguments is a valid case.


    16. What is the output of below code

    console.log(10 == [10]);
    console.log(10 == [[[[[[[10]]]]]]]);
    
    • 1: True, True
    • 2: True, False
    • 3: False, False
    • 4: False, True

    Answer

    Answer: 1

    As per the comparison algorithm in the ECMAScript specification(ECMA-262), the above expression converted into JS as below

    10 === Number([10].valueOf().toString()); // 10
    

    So it doesn't matter about number brackets([]) around the number, it is always converted to a number in the expression.


    17. What is the output of below code

    console.log(10 + "10");
    console.log(10 - "10");
    
    • 1: 20, 0
    • 2: 1010, 0
    • 3: 1010, 10-10
    • 4: NaN, NaN

    Answer

    Answer: 2

    The concatenation operator(+) is applicable for both number and string types. So if any operand is string type then both operands concatenated as strings. Whereas subtract(-) operator tries to convert the operands as number type.


    18. What is the output of below code

    console.log([0] == false);
    if ([0]) {
    console.log("I'm True");
    } else {
    console.log("I'm False");
    }
    
    • 1: True, I'm True
    • 2: True, I'm False
    • 3: False, I'm True
    • 4: False, I'm False

    Answer

    Answer: 1

    In comparison operators, the expression [0] converted to Number([0].valueOf().toString()) which is resolved to false. Whereas [0] just becomes a truthy value without any conversion because there is no comparison operator.

    19. What is the output of below code

    console.log([1, 2] + [3, 4]);
    
    • 1: [1,2,3,4]
    • 2: [1,2][3,4]
    • 3: SyntaxError
    • 4: 1,23,4

    Answer

    Answer: 4

    The + operator is not meant or defined for arrays. So it converts arrays into strings and concatenates them.


    20. What is the output of below code

    const numbers = new Set([1, 1, 2, 3, 4]);
    console.log(numbers);
    
    const browser = new Set("Firefox");
    console.log(browser);
    
    • 1: {1, 2, 3, 4}, {"F", "i", "r", "e", "f", "o", "x"}
    • 2: {1, 2, 3, 4}, {"F", "i", "r", "e", "o", "x"}
    • 3: [1, 2, 3, 4], ["F", "i", "r", "e", "o", "x"]
    • 4: {1, 1, 2, 3, 4}, {"F", "i", "r", "e", "f", "o", "x"}

    Answer

    Answer: 1

    Since Set object is a collection of unique values, it won't allow duplicate values in the collection. At the same time, it is case sensitive data structure.


    21. What is the output of below code

    console.log(NaN === NaN);
    
    • 1: True
    • 2: False

    Answer

    Answer: 2

    JavaScript follows IEEE 754 spec standards. As per this spec, NaNs are never equal for floating-point numbers.


    22. What is the output of below code

    let numbers = [1, 2, 3, 4, NaN];
    console.log(numbers.indexOf(NaN));
    
    • 1: 4
    • 2: NaN
    • 3: SyntaxError
    • 4: -1

    Answer

    Answer: 4

    The indexOf uses strict equality operator(===) internally and NaN === NaN evaluates to false. Since indexOf won't be able to find NaN inside an array, it returns -1 always. But you can use Array.prototype.findIndex method to find out the index of NaN in an array or You can use Array.prototype.includes to check if NaN is present in an array or not.

    let numbers = [1, 2, 3, 4, NaN];
    console.log(numbers.findIndex(Number.isNaN)); // 4
    
    console.log(numbers.includes(NaN)); // true
    

    23. What is the output of below code

    let [a, ...b, c] = [1, 2, 3, 4, 5];
    console.log(a, b, c);
    
    • 1: 1, [2, 3, 4, 5]
    • 2: 1, {2, 3, 4, 5}
    • 3: SyntaxError
    • 4: 1, [2, 3, 4]

    Answer

    Answer: 3

    When using rest parameters, trailing commas are not allowed and will throw a SyntaxError. If you remove the trailing comma and last element then it displays 1st answer

    let [a, ...b] = [1, 2, 3, 4, 5];
    console.log(a, b); // 1, [2, 3, 4, 5]
    

    25. What is the output of below code

    async function func() {
    return 10;
    }
    console.log(func());
    
    • 1: Promise {<fulfilled>: 10}
    • 2: 10
    • 3: SyntaxError
    • 4: Promise {<rejected>: 10}

    Answer

    Answer: 1

    Async functions always return a promise. But even if the return value of an async function is not explicitly a promise, it will be implicitly wrapped in a promise. The above async function is equivalent to below expression,

    function func() {
    return Promise.resolve(10);
    }
    

    26. What is the output of below code

    async function func() {
    await 10;
    }
    console.log(func());
    
    • 1: Promise {<fulfilled>: 10}
    • 2: 10
    • 3: SyntaxError
    • 4: Promise {<resolved>: undefined}

    Answer

    Answer: 4

    The await expression returns value 10 with promise resolution and the code after each await expression can be treated as existing in a .then callback. In this case, there is no return expression at the end of the function. Hence, the default return value of undefined is returned as the resolution of the promise. The above async function is equivalent to below expression,

    function func() {
    return Promise.resolve(10).then(() => undefined);
    }
    

    27. What is the output of below code

    function delay() {
    return new Promise(resolve => setTimeout(resolve, 2000));
    }
    
    async function delayedLog(item) {
    await delay();
    console.log(item);
    }
    
    async function processArray(array) {
    array.forEach(item => {
    await delayedLog(item);
    })
    }
    
    processArray([1, 2, 3, 4]);
    
    • 1: SyntaxError
    • 2: 1, 2, 3, 4
    • 3: 4, 4, 4, 4
    • 4: 4, 3, 2, 1

    Answer

    Answer: 1

    Even though “processArray” is an async function, the anonymous function that we use for forEach is synchronous. If you use await inside a synchronous function then it throws a syntax error.


    28. What is the output of below code

    function delay() {
    return new Promise((resolve) => setTimeout(resolve, 2000));
    }
    
    async function delayedLog(item) {
    await delay();
    console.log(item);
    }
    
    async function process(array) {
    array.forEach(async (item) => {
    await delayedLog(item);
    });
    console.log("Process completed!");
    }
    process([1, 2, 3, 5]);
    
    • 1: 1 2 3 5 and Process completed!
    • 2: 5 5 5 5 and Process completed!
    • 3: Process completed! and 5 5 5 5
    • 4: Process completed! and 1 2 3 5

    Answer

    Answer: 4

    The forEach method will not wait until all items are finished but it just runs the tasks and goes next. Hence, the last statement is displayed first followed by a sequence of promise resolutions.

    But you control the array sequence using for..of loop,

    async function processArray(array) {
    for (const item of array) {
    await delayedLog(item);
    }
    console.log("Process completed!");
    }
    

    29. What is the output of below code

    var set = new Set();
    set.add("+0").add("-0").add(NaN).add(undefined).add(NaN);
    console.log(set);
    
    • 1: Set(4) {"+0", "-0", NaN, undefined}
    • 2: Set(3) {"+0", NaN, undefined}
    • 3: Set(5) {"+0", "-0", NaN, undefined, NaN}
    • 4: Set(4) {"+0", NaN, undefined, NaN}

    Answer

    Answer: 1

    Set has few exceptions from equality check,

    1. All NaN values are equal
    2. Both +0 and -0 considered as different values

    30. What is the output of below code

    const sym1 = Symbol("one");
    const sym2 = Symbol("one");
    
    const sym3 = Symbol.for("two");
    const sym4 = Symbol.for("two");
    
    console.log(sym1 === sym2, sym3 === sym4);
    
    • 1: true, true
    • 2: true, false
    • 3: false, true
    • 4: false, false

    Answer

    Answer: 3

    Symbol follows below conventions,

    1. Every symbol value returned from Symbol() is unique irrespective of the optional string.
    2. Symbol.for() function creates a symbol in a global symbol registry list. But it doesn't necessarily create a new symbol on every call, it checks first if a symbol with the given key is already present in the registry and returns the symbol if it is found. Otherwise a new symbol created in the registry.

    Note: The symbol description is just useful for debugging purposes.


    31. What is the output of below code

    const sym1 = new Symbol("one");
    console.log(sym1);
    
    • 1: SyntaxError
    • 2: one
    • 3: Symbol('one')
    • 4: Symbol

    Answer

    Answer: 1

    Symbol is a just a standard function and not an object constructor(unlike other primitives new Boolean, new String and new Number). So if you try to call it with the new operator will result in a TypeError


    32. What is the output of below code

    let myNumber = 100;
    let myString = "100";
    
    if (!typeof myNumber === "string") {
    console.log("It is not a string!");
    } else {
    console.log("It is a string!");
    }
    
    if (!typeof myString === "number") {
    console.log("It is not a number!");
    } else {
    console.log("It is a number!");
    }
    
    • 1: SyntaxError
    • 2: It is not a string!, It is not a number!
    • 3: It is not a string!, It is a number!
    • 4: It is a string!, It is a number!

    Answer

    Answer: 4

    The return value of typeof myNumber or typeof myString is always a truthy value (either "number" or "string"). The ! operator operates on either typeof myNumber or typeof myString, converting them to boolean values. Since the value of both !typeof myNumber and !typeof myString is false, the if condition fails, and control goes to else block.

    To make the ! operator operate on the equality expression, one needs to add parentheses:

    if (!(typeof myNumber === "string"))
    

    Or simply use the inequality operator:

    if (typeof myNumber !== "string")
    

    33. What is the output of below code

    console.log(
    JSON.stringify({ myArray: ["one", undefined, function () {}, Symbol("")] })
    );
    console.log(
    JSON.stringify({ [Symbol.for("one")]: "one" }, [Symbol.for("one")])
    );
    
    • 1: {"myArray":['one', undefined, {}, Symbol]}, {}
    • 2: {"myArray":['one', null,null,null]}, {}
    • 3: {"myArray":['one', null,null,null]}, "{ [Symbol.for('one')]: 'one' }, [Symbol.for('one')]"
    • 4: {"myArray":['one', undefined, function(){}, Symbol('')]}, {}

    Answer

    Answer: 2

    The symbols has below constraints,

    1. The undefined, Functions, and Symbols are not valid JSON values. So those values are either omitted (in an object) or changed to null (in an array). Hence, it returns null values for the value array.
    2. All Symbol-keyed properties will be completely ignored. Hence it returns an empty object({}).

    34. What is the output of below code

    class A {
    constructor() {
    console.log(new.target.name);
    }
    }
    
    class B extends A {
    constructor() {
    super();
    }
    }
    
    new A();
    new B();
    
    • 1: A, A
    • 2: A, B

    Answer

    Answer: 2

    Using constructors, new.target refers to the constructor (points to the class definition of class which is initialized) that was directly invoked by new. This also applies to the case if the constructor is in a parent class and was delegated from a child constructor.


    35. What is the output of below code

    const [x, ...y, z] = [1, 2, 3, 4];
    console.log(x, y, z);
    
    • 1: 1, [2, 3], 4
    • 2: 1, [2, 3, 4], undefined
    • 3: 1, [2], 3
    • 4: SyntaxError

    Answer

    Answer: 4

    It throws a syntax error because the rest element should not have a trailing comma. You should always consider using a rest operator as the last element.


    36. What is the output of below code

    const { a: x = 10, b: y = 20 } = { a: 30 };
    
    console.log(x);
    console.log(y);
    
    • 1: 30, 20
    • 2: 10, 20
    • 3: 10, undefined
    • 4: 30, undefined

    Answer

    Answer: 1

    The object property follows below rules,

    1. The object properties can be retrieved and assigned to a variable with a different name
    2. The property assigned a default value when the retrieved value is undefined

    37. What is the output of below code

    function area({ length = 10, width = 20 }) {
    console.log(length * width);
    }
    
    area();
    
    • 1: 200
    • 2: Error
    • 3: undefined
    • 4: 0

    Answer

    Answer: 2

    If you leave out the right-hand side assignment for the destructuring object, the function will look for at least one argument to be supplied when invoked. Otherwise you will receive an error Error: Cannot read property 'length' of undefined as mentioned above.

    You can avoid the error with either of the below changes,

    1. Pass at least an empty object:
    function area({ length = 10, width = 20 }) {
    console.log(length * width);
    }
    
    area({});
    
    1. Assign default empty object:
    function area({ length = 10, width = 20 } = {}) {
    console.log(length * width);
    }
    
    area();
    

    38. What is the output of below code

    const props = [
    { id: 1, name: "John" },
    { id: 2, name: "Jack" },
    { id: 3, name: "Tom" },
    ];
    
    const [, , { name }] = props;
    console.log(name);
    
    • 1: Tom
    • 2: Error
    • 3: undefined
    • 4: John

    Answer

    Answer: 1

    It is possible to combine Array and Object destructuring. In this case, the third element in the array props accessed first followed by name property in the object.


    39. What is the output of below code

    function checkType(num = 1) {
    console.log(typeof num);
    }
    
    checkType();
    checkType(undefined);
    checkType("");
    checkType(null);
    
    • 1: number, undefined, string, object
    • 2: undefined, undefined, string, object
    • 3: number, number, string, object
    • 4: number, number, number, number

    Answer

    Answer: 3

    If the function argument is set implicitly(not passing argument) or explicitly to undefined, the value of the argument is the default parameter. Whereas for other falsy values('' or null), the value of the argument is passed as a parameter.

    Hence, the result of function calls categorized as below,

    1. The first two function calls logs number type since the type of default value is number
    2. The type of '' and null values are string and object type respectively.

    40. What is the output of below code

    function add(item, items = []) {
    items.push(item);
    return items;
    }
    
    console.log(add("Orange"));
    console.log(add("Apple"));
    
    • 1: ['Orange'], ['Orange', 'Apple']
    • 2: ['Orange'], ['Apple']

    Answer

    Answer: 2

    Since the default argument is evaluated at call time, a new object is created each time the function is called. So in this case, the new array is created and an element pushed to the default empty array.


    41. What is the output of below code

    function greet(greeting, name, message = greeting + " " + name) {
    console.log([greeting, name, message]);
    }
    
    greet("Hello", "John");
    greet("Hello", "John", "Good morning!");
    
    • 1: SyntaxError
    • 2: ['Hello', 'John', 'Hello John'], ['Hello', 'John', 'Good morning!']

    Answer

    Answer: 2

    Since parameters defined earlier are available to later default parameters, this code snippet doesn't throw any error.


    42. What is the output of below code

    function outer(f = inner()) {
    function inner() {
    return "Inner";
    }
    }
    outer();
    
    • 1: ReferenceError
    • 2: Inner

    Answer

    Answer: 1

    The functions and variables declared in the function body cannot be referred from default value parameter initializers. If you still try to access, it throws a run-time ReferenceError(i.e, inner is not defined).


    43. What is the output of below code

    function myFun(x, y, ...manyMoreArgs) {
    console.log(manyMoreArgs);
    }
    
    myFun(1, 2, 3, 4, 5);
    myFun(1, 2);
    
    • 1: [3, 4, 5], undefined
    • 2: SyntaxError
    • 3: [3, 4, 5], []
    • 4: [3, 4, 5], [undefined]

    Answer

    Answer: 3

    The rest parameter is used to hold the remaining parameters of a function and it becomes an empty array if the argument is not provided.


    44. What is the output of below code

    const obj = { key: "value" };
    const array = [...obj];
    console.log(array);
    
    • 1: ['key', 'value']
    • 2: TypeError
    • 3: []
    • 4: ['key']

    Answer

    Answer: 2

    Spread syntax can be applied only to iterable objects. By default, Objects are not iterable, but they become iterable when used in an Array, or with iterating functions such as map(), reduce(), and assign(). If you still try to do it, it still throws TypeError: obj is not iterable.


    45. What is the output of below code

    function* myGenFunc() {
    yield 1;
    yield 2;
    yield 3;
    }
    var myGenObj = new myGenFunc();
    console.log(myGenObj.next().value);
    
    • 1: 1
    • 2: undefined
    • 3: SyntaxError
    • 4: TypeError

    Answer

    Answer: 4

    Generators are not constructible type. But if you still proceed to do, there will be an error saying "TypeError: myGenFunc is not a constructor"


    46. What is the output of below code

    function* yieldAndReturn() {
    yield 1;
    return 2;
    yield 3;
    }
    
    var myGenObj = yieldAndReturn();
    console.log(myGenObj.next());
    console.log(myGenObj.next());
    console.log(myGenObj.next());
    
    • 1: { value: 1, done: false }, { value: 2, done: true }, { value: undefined, done: true }
    • 2: { value: 1, done: false }, { value: 2, done: false }, { value: undefined, done: true }
    • 3: { value: 1, done: false }, { value: 2, done: true }, { value: 3, done: true }
    • 4: { value: 1, done: false }, { value: 2, done: false }, { value: 3, done: true }

    Answer

    Answer: 1

    A return statement in a generator function will make the generator finish. If a value is returned, it will be set as the value property of the object and done property to true. When a generator is finished, subsequent next() calls return an object of this form: {value: undefined, done: true}.


    47. What is the output of below code

    const myGenerator = (function* () {
    yield 1;
    yield 2;
    yield 3;
    })();
    for (const value of myGenerator) {
    console.log(value);
    break;
    }
    
    for (const value of myGenerator) {
    console.log(value);
    }
    
    • 1: 1,2,3 and 1,2,3
    • 2: 1,2,3 and 4,5,6
    • 3: 1 and 1
    • 4: 1

    Answer

    Answer: 4

    The generator should not be re-used once the iterator is closed. i.e, Upon exiting a loop(on completion or using break & return), the generator is closed and trying to iterate over it again does not yield any more results. Hence, the second loop doesn't print any value.


    48. What is the output of below code

    const num = 0o38;
    console.log(num);
    
    • 1: SyntaxError
    • 2: 38

    Answer

    Answer: 1

    If you use an invalid number(outside of 0-7 range) in the octal literal, JavaScript will throw a SyntaxError. In ES5, it treats the octal literal as a decimal number.


    49. What is the output of below code

    const squareObj = new Square(10);
    console.log(squareObj.area);
    
    class Square {
    constructor(length) {
    this.length = length;
    }
    
    get area() {
    return this.length * this.length;
    }
    
    set area(value) {
    this.area = value;
    }
    }
    
    • 1: 100
    • 2: ReferenceError

    Answer

    Answer: 2

    Unlike function declarations, class declarations are not hoisted. i.e, First You need to declare your class and then access it, otherwise it will throw a ReferenceError "Uncaught ReferenceError: Square is not defined".

    Note: Class expressions also applies to the same hoisting restrictions of class declarations.


    50. What is the output of below code

    function Person() {}
    
    Person.prototype.walk = function () {
    return this;
    };
    
    Person.run = function () {
    return this;
    };
    
    let user = new Person();
    let walk = user.walk;
    console.log(walk());
    
    let run = Person.run;
    console.log(run());
    
    • 1: undefined, undefined
    • 2: Person, Person
    • 3: SyntaxError
    • 4: Window, Window

    Answer

    Answer: 4

    When a regular or prototype method is called without a value for this, the methods return an initial this value if the value is not undefined. Otherwise global window object will be returned. In our case, the initial this value is undefined so both methods return window objects.


    51. What is the output of below code

    class Vehicle {
    constructor(name) {
    this.name = name;
    }
    
    start() {
    console.log(`${this.name} vehicle started`);
    }
    }
    
    class Car extends Vehicle {
    start() {
    console.log(`${this.name} car started`);
    super.start();
    }
    }
    
    const car = new Car("BMW");
    console.log(car.start());
    
    • 1: SyntaxError
    • 2: BMW vehicle started, BMW car started
    • 3: BMW car started, BMW vehicle started
    • 4: BMW car started, BMW car started

    Answer

    Answer: 3

    The super keyword is used to call methods of a superclass. Unlike other languages the super invocation doesn't need to be a first statement. i.e, The statements will be executed in the same order of code.


    52. What is the output of below code

    const USER = { age: 30 };
    USER.age = 25;
    console.log(USER.age);
    
    • 1: 30
    • 2: 25
    • 3: Uncaught TypeError
    • 4: SyntaxError

    Answer

    Answer: 2

    Even though we used constant variables, the content of it is an object and the object's contents (e.g properties) can be altered. Hence, the change is going to be valid in this case.


    53. What is the output of below code

    console.log("🙂" === "🙂");
    
    • 1: false
    • 2: true

    Answer

    Answer: 2

    Emojis are unicodes and the unicode for smile symbol is "U+1F642". The unicode comparison of same emojies is equivalent to string comparison. Hence, the output is always true.


    54. What is the output of below code?

    console.log(typeof typeof typeof true);
    
    • 1: string
    • 2: boolean
    • 3: NaN
    • 4: number

    Answer

    Answer: 1

    The typeof operator on any primitive returns a string value. So even if you apply the chain of typeof operators on the return value, it is always string.


    55. What is the output of below code?

    let zero = new Number(0);
    
    if (zero) {
    console.log("If");
    } else {
    console.log("Else");
    }
    
    • 1: If
    • 2: Else
    • 3: NaN
    • 4: SyntaxError

    Answer

    Answer: 1
    1. The type of operator on new Number always returns object. i.e, typeof new Number(0) --> object.
    2. Objects are always truthy in if block

    Hence the above code block always goes to if section.


    55. What is the output of below code in non strict mode?

    let msg = "Good morning!!";
    
    msg.name = "John";
    
    console.log(msg.name);
    
    • 1: ""
    • 2: Error
    • 3: John
    • 4: Undefined

    Answer

    Answer: 4

    It returns undefined for non-strict mode and returns Error for strict mode. In non-strict mode, the wrapper object is going to be created and get the mentioned property. But the object get disappeared after accessing the property in next line.


    56. What is the output of below code?

    let count = 10;
    
    (function innerFunc() {
    if (count === 10) {
    let count = 11;
    console.log(count);
    }
    console.log(count);
    })();
    
    • 1: 11, 10
    • 2: 11, 11
    • 3: 10, 11
    • 4: 10, 10

    Answer

    Answer: 1

    11 and 10 is logged to the console.

    The innerFunc is a closure which captures the count variable from the outerscope. i.e, 10. But the conditional has another local variable count which overwrites the ourter count variable. So the first console.log displays value 11. Whereas the second console.log logs 10 by capturing the count variable from outerscope.


    57. What is the output of below code ?

    • 1: console.log(true && 'hi');
    • 2: console.log(true && 'hi' && 1);
    • 3: console.log(true && '' && 0);

    Answer

    • 1: hi
    • 2: 1
    • 3: ''

    Reason : The operator returns the value of the first falsy operand encountered when evaluating from left to right, or the value of the last operand if they are all truthy.

    Note: Below these values are consider as falsy value

    • 1: 0
    • 2: ''
    • 3: null
    • 4: undefined
    • 5: NAN

    58. What is the output of below code ?

    let arr = [1, 2, 3];
    let str = "1,2,3";
    
    console.log(arr == str);
    
    • 1: false
    • 2: Error
    • 3: true

    Answer

    Answer: 3

    Arrays have their own implementation of toString method that returns a comma-separated list of elements. So the above code snippet returns true. In order to avoid conversion of array type, we should use === for comparison.


    59. What is the output of below code?

    getMessage();
    
    var getMessage = () => {
    console.log("Good morning");
    };
    
    • 1: Good morning
    • 2: getMessage is not a function
    • 3: getMessage is not defined
    • 4: Undefined

    Answer

    Answer: 2

    Hoisting will move variables and functions to be the top of scope. Even though getMessage is an arrow function the above function will considered as a variable due to it's variable declaration or assignment. So the variables will have undefined value in memory phase and throws an error 'getMessage is not a function' at the code execution phase.


    60. What is the output of below code?

    let quickPromise = Promise.resolve();
    
    quickPromise.then(() => console.log("promise finished"));
    
    console.log("program finished");
    
    • 1: program finished
    • 2: Cannot predict the order
    • 3: program finished, promise finished
    • 4: promise finished, program finished

    Answer

    Answer: 3

    Even though a promise is resolved immediately, it won't be executed immediately because its .then/catch/finally handlers or callbacks(aka task) are pushed into the queue. Whenever the JavaScript engine becomes free from the current program, it pulls a task from the queue and executes it. This is the reason why last statement is printed first before the log of promise handler.

    Note: We call the above queue as "MicroTask Queue"


    61. What is the output of below code?

    console
    .log("First line")
    [("a", "b", "c")].forEach((element) => console.log(element));
    console.log("Third line");
    
    • 1: First line, then print a, b, c in a new line, and finally print Third line as next line
    • 2: First line, then print a, b, c in a first line, and print Third line as next line
    • 3: Missing semi-colon error
    • 4: Cannot read properties of undefined

    Answer

    Answer: 4

    When JavaScript encounters a line break without a semicolon, the JavaScript parser will automatically add a semicolon based on a set of rules called Automatic Semicolon Insertion which determines whether line break as end of statement or not to insert semicolon. But it does not assume a semicolon before square brackets [...]. So the first two lines considered as a single statement as below.

    console
    .log("First line")
    [("a", "b", "c")].forEach((element) => console.log(element));
    

    Hence, there will be cannot read properties of undefined error while applying the array square bracket on log function.


    62. Write a function that returns a random HEX color

    Solution 1 (Iterative generation)

    const HEX_ALPHABET = [
    "0",
    "1",
    "2",
    "3",
    "4",
    "5",
    "6",
    "7",
    "8",
    "9",
    "a",
    "b",
    "c",
    "d",
    "e",
    "f",
    ];
    const HEX_PREFIX = "#";
    const HEX_LENGTH = 6;
    
    function generateRandomHex() {
    let randomHex = "";
    
    for (let i = 0; i < HEX_LENGTH; i++) {
    const randomIndex = Math.floor(Math.random() * HEX_ALPHABET.length);
    randomHex += HEX_ALPHABET[randomIndex];
    }
    
    return HEX_PREFIX + randomHex;
    }
    

    Solution 2 (One-liner)

    const HEX_PREFIX = "#";
    const HEX_RADIX = 16;
    const HEX_LENGTH = 6;
    
    function generateRandomHex() {
    return (
    HEX_PREFIX +
    Math.floor(Math.random() * 0xffffff)
    .toString(HEX_RADIX)
    .padStart(HEX_LENGTH, "0")
    );
    }
    

    63. What is the output of below code?

    var of = ["of"];
    for (var of of of) {
    console.log(of);
    }
    
    • 1: of
    • 2: SyntaxError: Unexpected token of
    • 3: SyntaxError: Identifier 'of' has already been declared
    • 4: ReferenceError: of is not defined

    Answer

    Answer: 1

    In JavaScript, of is not considered as a reserved keyword. So the variable declaration with of is accepted and prints the array value of using for..of loop.

    But if you use reserved keyword such as in then there will be a syntax error saying SyntaxError: Unexpected token in,

    var in = ['in'];
    for(var in in in) {
    console.log(in[in]);
    }
    

    64. What is the output of below code?

    const numbers = [11, 25, 31, 23, 33, 18, 200];
    numbers.sort();
    console.log(numbers);
    
    • 1: [11, 18, 23, 25, 31, 33, 200]
    • 2: [11, 18, 200, 23, 25, 31, 33]
    • 3: [11, 25, 31, 23, 33, 18, 200]
    • 4: Cannot sort numbers

    Answer

    Answer: 2

    By default, the sort method sorts elements alphabetically. This is because elemented converted to strings and strings compared in UTF-16 code units order. Hence, you will see the above numbers not sorted as expected. In order to sort numerically just supply a comparator function which handles numeric sorts.

    const numbers = [11, 25, 31, 23, 33, 18, 200];
    numbers.sort((a, b) => a - b);
    console.log(numbers);
    

    Note: Sort() method changes the original array.


    65. What is the output order of below code?

    setTimeout(() => {
    console.log("1");
    }, 0);
    Promise.resolve("hello").then(() => console.log("2"));
    console.log("3");
    
    • 1: 1, 2, 3
    • 2: 1, 3, 2
    • 3: 3, 1, 2
    • 4: 3, 2, 1

    Answer

    Answer: 4

    When the JavaScript engine parses the above code, the first two statements are asynchronous which will be executed later and third statement is synchronous statement which will be moved to callstack, executed and prints the number 3 in the console. Next, Promise is native in ES6 and it will be moved to Job queue which has high priority than callback queue in the execution order. At last, since setTimeout is part of WebAPI the callback function moved to callback queue and executed. Hence, you will see number 2 printed first followed by 1.


    66. What is the output of below code?

    console.log(name);
    console.log(message());
    var name = "John";
    (function message() {
    console.log("Hello John: Welcome");
    });
    
    • 1: John, Hello John: Welcome
    • 2: undefined, Hello John, Welcome
    • 3: Reference error: name is not defined, Reference error: message is not defined
    • 4: undefined, Reference error: message is not defined

    Answer

    Answer: 4

    IIFE(Immediately Invoked Function Expression) is just like any other function expression which won't be hoisted. Hence, there will be a reference error for message call. The behavior would be the same with below function expression of message1,

    console.log(name);
    console.log(message());
    var name = 'John';
    var message = function () {
    console.log('Hello John: Welcome');
    });
    

    67. What is the output of below code?

    message();
    
    function message() {
    console.log("Hello");
    }
    function message() {
    console.log("Bye");
    }
    
    • 1: Reference error: message is not defined
    • 2: Hello
    • 3: Bye
    • 4: Compile time error

    Answer

    Answer: 3

    As part of hoisting, initially JavaScript Engine or compiler will store first function in heap memory but later rewrite or replaces with redefined function content.


    68. What is the output of below code?

    var currentCity = "NewYork";
    
    var changeCurrentCity = function () {
    console.log("Current City:", currentCity);
    var currentCity = "Singapore";
    console.log("Current City:", currentCity);
    };
    
    changeCurrentCity();
    
    • 1: NewYork, Singapore
    • 2: NewYork, NewYork
    • 3: undefined, Singapore
    • 4: Singapore, Singapore

    Answer

    Answer: 3

    Due to hositing feature, the variables declared with var will have undefined value in the creation phase so the outer variable currentCity will get same undefined value. But after few lines of code JavaScript engine found a new function call(changeCurrentCity()) to update the current city with var re-declaration. Since each function call will create a new execution context, the same variable will have undefined value before the declaration and new value(Singapore) after the declaration. Hence, the value undefined print first followed by new value Singapore in the execution phase.


    69. What is the output of below code in an order?

    function second() {
    var message;
    console.log(message);
    }
    
    function first() {
    var message = "first";
    second();
    console.log(message);
    }
    
    var message = "default";
    first();
    console.log(message);
    
    • 1: undefined, first, default
    • 2: default, default, default
    • 3: first, first, default
    • 4: undefined, undefined, undefined

    Answer

    Answer: 1

    Each context(global or functional) has it's own variable environment and the callstack of variables in a LIFO order. So you can see the message variable value from second, first functions in an order followed by global context message variable value at the end.


    70. What is the output of below code?

    var expressionOne = function functionOne() {
    console.log("functionOne");
    };
    functionOne();
    
    • 1: functionOne is not defined
    • 2: functionOne
    • 3: console.log("functionOne")
    • 4: undefined

    Answer

    Answer: 1

    The function call functionOne is not going to be part of scope chain and it has it's own execution context with the enclosed variable environment. i.e, It won't be accessed from global context. Hence, there will be an error while invoking the function as functionOne is not defined.


    71. What is the output of below code?

    const user = {
    name: "John",
    eat() {
    console.log(this);
    var eatFruit = function () {
    console.log(this);
    };
    eatFruit();
    },
    };
    user.eat();
    
    • 1: {name: "John", eat: f}, {name: "John", eat: f}
    • 2: Window {...}, Window {...}
    • 3: {name: "John", eat: f}, undefined
    • 4: {name: "John", eat: f}, Window {...}

    Answer

    Answer: 4

    this keyword is dynamic scoped but not lexically scoped . In other words, it doesn't matter where this has been written but how it has been invoked really matter. In the above code snippet, the user object invokes eat function so this keyword refers to user object but eatFruit has been invoked by eat function and this will have default Window object.

    The above pit fall fixed by three ways,

    1. In ES6, the arrow function will make this keyword as lexically scoped. Since the surrounding object of this object is user object, the eatFruit function will contain user object for this object.
    const user = {
    name: "John",
    eat() {
    console.log(this);
    var eatFruit = () => {
    console.log(this);
    };
    eatFruit();
    },
    };
    user.eat();
    

    The next two solutions have been used before ES6 introduced.

    1. It is possible create a reference of this into a separate variable and use that new variable inplace of this keyword inside eatFruit function. This is a common practice in jQuery and AngularJS before ES6 introduced.
    const user = {
    name: "John",
    eat() {
    console.log(this);
    var self = this;
    var eatFruit = () => {
    console.log(self);
    };
    eatFruit();
    },
    };
    user.eat();
    
    1. The eatFruit function can bind explicitly with this keyword where it refers Window object.
    const user = {
    name: "John",
    eat() {
    console.log(this);
    var eatFruit = function () {
    console.log(this);
    };
    return eatFruit.bind(this);
    },
    };
    user.eat()();
    

    72. What is the output of below code?

    let message = "Hello World!";
    message[0] = "J";
    console.log(message);
    
    let name = "John";
    name = name + " Smith";
    console.log(name);
    
    • 1: Jello World!, John Smith
    • 2: Jello World!, John
    • 3: Hello World!, John Smith
    • 4: Hello World!, John

    Answer

    Answer: 3

    In JavaScript, primitives are immutable i.e. there is no way to change a primitive value once it gets created. So when you try to update the string's first character, there is no change in the string value and prints the same initial value Hello World!. Whereas in the later example, the concatenated value is re-assigned to the same variable which will result into creation of new memory block with the reference pointing to John Smith value and the old memory block value(John) will be garbage collected.


    73. What is the output of below code?

    let user1 = {
    name: "Jacob",
    age: 28,
    };
    
    let user2 = {
    name: "Jacob",
    age: 28,
    };
    
    console.log(user1 === user2);
    
    • 1: True
    • 2: False
    • 3: Compile time error

    Answer

    Answer: 2

    In JavaScript, the variables such as objects, arrays and functions comes under pass by reference. When you try to compare two objects with same content, it is going to compare memory address or reference of those variables. These variables always create separate memory blocks hence the comparison is always going to return false value.


    74. What is the output of below code?

    function greeting() {
    setTimeout(function () {
    console.log(message);
    }, 5000);
    const message = "Hello, Good morning";
    }
    greeting();
    
    • 1: Undefined
    • 2: Reference error:
    • 3: Hello, Good morning
    • 4: null

    Answer

    Answer: 3

    The variable message is still treated as closure(since it has been used in inner function) eventhough it has been declared after setTimeout function. The function with in setTimeout function will be sent to WebAPI and the variable declaration executed with in 5 seconds with the assigned value. Hence, the text declared for the variable will be displayed.


    75. What is the output of below code?

    const a = new Number(10);
    const b = 10;
    console.log(a === b);
    
    • 1: False
    • 2: True

    Answer

    Answer: 1

    Eventhough both variables a and b refer a number value, the first declaration is based on constructor function and the type of the variable is going to be object type. Whereas the second declaration is primitive assignment with a number and the type is number type. Hence, the equality operator === will output false value.


    76. What is the type of below function?

    function add(a, b) {
    console.log("The input arguments are: ", a, b);
    return a + b;
    }
    
    • 1: Pure function
    • 2: Impure function

    Answer

    Answer: 2

    Eventhough the above function returns the same result for the same arguments(input) that are passed in the function, the console.log() statement causes a function to have side effects because it affects the state of an external code. i.e, the console object's state and depends on it to perform the job. Hence, the above function considered as impure function.


    77. What is the output of below code?

    const promiseOne = new Promise((resolve, reject) => setTimeout(resolve, 4000));
    const promiseTwo = new Promise((resolve, reject) => setTimeout(reject, 4000));
    
    Promise.all([promiseOne, promiseTwo]).then((data) => console.log(data));
    
    • 1: [{status: "fulfilled", value: undefined}, {status: "rejected", reason: undefined}]
    • 2: [{status: "fulfilled", value: undefined}, Uncaught(in promise)]
    • 3: Uncaught (in promise)
    • 4: [Uncaught(in promise), Uncaught(in promise)]

    Answer

    Answer: 3

    The above promises settled at the same time but one of them resolved and other one rejected. When you use .all method on these promises, the result will be short circuted by throwing an error due to rejection in second promise. But If you use .allSettled method then result of both the promises will be returned irrespective of resolved or rejected promise status without throwing any error.

    Promise.allSettled([promiseOne, promiseTwo]).then((data) => console.log(data));
    

    78. What is the output of below code?

    try {
    setTimeout(() => {
    console.log("try block");
    throw new Error(`An exception is thrown`);
    }, 1000);
    } catch (err) {
    console.log("Error: ", err);
    }
    
    • 1: try block, Error: An exception is thrown
    • 2: Error: An exception is thrown
    • 3: try block, Uncaught Error: Exception is thrown
    • 4: Uncaught Error: Exception is thrown

    Answer

    Answer: 3

    If you put setTimeout and setInterval methods inside the try clause and an exception is thrown, the catch clause will not catch any of them. This is because the try...catch statement works synchronously, and the function in the above code is executed asynchronously after a certain period of time. Hence, you will see runtime exception without catching the error. To resolve this issue, you have to put the try...catch block inside the function as below,

    setTimeout(() => {
    try {
    console.log("try block");
    throw new Error(`An exception is thrown`);
    } catch (err) {
    console.log("Error: ", err);
    }
    }, 1000);
    

    You can use .catch() function in promises to avoid these issues with asynchronous code.


    79. What is the output of below code?

    let a = 10;
    if (true) {
    let a = 20;
    console.log(a, "inside");
    }
    console.log(a, "outside");
    
    • 1: 20, "inside" and 20, "outside"
    • 2: 20, "inside" and 10, "outside"
    • 3: 10, "inside" and 10, "outside"
    • 4: 10, "inside" and 20, "outside"

    Answer

    Answer: 2

    The variable "a" declared inside "if" has block scope and does not affect the value of the outer "a" variable.


    80. What is the output of below code?

    let arr = [1, 2, 3, 4, 5, -6, 7];
    arr.length = 0;
    console.log(arr);
    
    • 1: 0
    • 2: Undefined
    • 3: null
    • 4: [ ]

    Answer

    Answer: 4

    The length of the array 'arr' has been set to 0, so the array becomes empty.


    81. How do you verify two strings are anagrams or not?

    An anagram is a word or phrase formed by rearranging all the letters of a different word or phrase exactly once. For example, the anagrams of "eat" word are "tea" and "ate".

    You can split each word into characters, followed by sort action and later join them back. After that you can compare those two words to verify whether those two words are anagrams or not.

    function verifyAnagrams(word1, word2) {
    return word1.split("").sort().join("") === word2.split("").sort().join("");
    }
    console.log(verifyAnagrams("eat", "ate"));
    

    82. What is the output of below code?

    printHello();
    
    printMessage();
    
    function printHello() {
    console.log("Hello");
    
    function printMessage() {
    console.log("Good day");
    }
    }
    
    • 1: Hello, Good day
    • 2: Reference Error: printHello is not defined, Reference Error: printMessage is not defined
    • 3: Reference Error: printHello is not defined, Good day
    • 4: Hello, Reference Error: printMessage is not defined

    Answer

    Answer: 4

    The function printHello is hoisted to the top of the global scope and prints "Hello" to the console. Even printMessage function is hoisted, but it is lifted to the local scope(in "printHello") it was declared in. That is the reason you will endup with reference error for second function call.

    But if the second function is invoked in the first function itself, there won't be any reference error.

    printHello();
    
    function printHello() {
    printMessage();
    console.log("Hello");
    
    function printMessage() {
    console.log("Good day");
    }
    }
    

    83. What is the time taken to execute below timeout callback?

    console.log("Start code");
    
    setTimeout(function () {
    console.log("Callback code");
    }, 5000);
    
    console.log("After callback");
    
    let startTime = new Date().getTime();
    let endTime = startTime;
    
    while (endTime <= startTime + 10000) {
    endTime = new Date().getTime();
    }
    
    console.log("End code");
    
    • 1: > 10 sec
    • 2: Immediately
    • 3: < 10 sec
    • 4: <= 5sec

    Answer

    Answer: 1

    Even though there is a timer of 5 seconds supplied to setTimeout callback, it won't get executed until the main thread is free and finished executing the remaining part of the code. In this example, the remaining code(while loop) takes 10seconds to finish it's execution. In the mean time, the callback will be stored in callback queue upon completion of its 5 seconds timer. After 10 seconds, the callback will be moved to callstack because the callstack is empty by poping out global execution context.

    84. What is the output of below code?

    let arr = ["wöchentlich", "Woche", "wäre", "Wann"];
    console.log(arr.sort());
    
    • 1: ['wöchentlich','Woche', 'wäre', 'Wann']
    • 2: ['Wann', 'wäre', 'Woche', 'wöchentlich']
    • 3: ['Wann', 'Woche', 'wäre', 'wöchentlich']
    • 4: ['wäre', 'Wann', 'wöchentlich','Woche']

    Answer

    Answer: 3

    JavaScript has a native method sort that allows sorting an array of elements in-place. It will treat each element as a string and sort it alphabetically. But if you try to sort an array of strings which has non-ASCII characters, you will receive a strange result. This is because characters with an accent have higher character codes.

    In this case, the sort order of an array is ['Wann', 'Woche', 'wäre', 'wöchentlich'].

    If you want to sort an array of string values which has non-ASCII characters in an ascending order, there are two possible options like localeCompare and Intl.Collator provided by ECMAScript Internationalization API.

    localeCompare:

    let arr = ["wöchentlich", "Woche", "wäre", "Wann"];
    console.log(arr.sort((a, b) => a.localeCompare(b))); //['Wann', 'wäre', 'Woche', 'wöchentlich']
    

    Intl.Collator:

    let arr = ["wöchentlich", "Woche", "wäre", "Wann"];
    console.log(arr.sort(Intl.Collator().compare)); //['Wann', 'wäre', 'Woche', 'wöchentlich']
    

    85. What is the output of below code?

    function func(a, b = 2) {
    console.log(arguments.length);
    }
    
    func(undefined);
    func();
    
    • 1: 1, 0
    • 2: 0, 0
    • 3: 0, 1
    • 4: 1, 1

    Answer

    Answer: 1

    If a function is called with undefined, the undefined value is treated as a parameter. But if the function is not passed with any parameters, the arguments object doesn't include any argument eventhough the function has default function parameter. Hence, the function invocation with undefined has one argument and function call without any arguments has 0 arguments.

    86. What is the output of below code?

    const numbers = [1, 2, 3];
    
    // Count how many numbers are odd
    let xorAccumulator = numbers.reduce((sum, value) => {
    return sum + (value % 2);
    }, 0);
    
    // IIFE applying XOR of each element shifted by its index
    (function(arr) {
    for (let index = 0; index < arr.length; index++) {
    xorAccumulator ^= (arr[index] << index);
    }
    })(numbers);
    
    console.log(xorAccumulator);
    
    
    • 1: 5
    • 2: 7
    • 3: 11
    • 4: 1

    Answer

    Answer: 3

    This question is really showcasing how JavaScript mixes array reduction with low-level bitwise tricks. The code first uses .reduce() to turn the array into a single value by counting how many elements are odd, then an IIFE immediately kicks in and loops through the array again, shifting each number left by its index and XOR-ing it into the accumulator. The whole vibe is about understanding how reduction works for summarizing arrays and how bit shifting plus XOR can transform values in a way that feels mathematical rather than typical JS.

Get LinkedIn Premium at Rs 399