FrontendDeveloper.in

JavaScript Interview Questions

  • Question 16

    What is a pure function

    A pure function is a function whose output depends only on its input arguments and produces no side effects. This means that given the same inputs, a pure function will always return the same output, and it does not modify any external state or data.

    Let's take an example to see the difference between pure and impure functions,

    Example: Pure vs. Impure Functions

    // Impure Function
    let numberArray = [];
    const impureAddNumber = (number) => numberArray.push(number);
    
    // Pure Function
    const pureAddNumber = (number) => (inputArray) =>
    inputArray.concat([number]);
    
    // Usage
    console.log(impureAddNumber(6)); // returns 1
    console.log(numberArray);        // returns [6]
    
    console.log(pureAddNumber(7)(numberArray)); // returns [6, 7]
    console.log(numberArray);                   // remains [6]
    
    • impureAddNumber changes the external variable numberArray and returns the new length of the array, making it impure.
    • pureAddNumber creates a new array with the added number and does not modify the original array, making it pure.
  • Question 17

    What are the benefits of pure functions

    Some of the major benefits of pure functions are listed below,

    • Easier testing: Since output depends only on input, pure functions are simple to test.
    • Predictability: No hidden side effects make behavior easier to reason about.
    • Immutability: Pure functions align with ES6 best practices, such as preferring const over let, supporting safer and more maintainable code.
    • No side effects: Reduces bugs related to shared state or mutation.
  • Question 18

    What is the purpose of the let keyword

    The let keyword in JavaScript is used to declare a block-scoped local variable. This means that variables declared with let are only accessible within the block, statement, or expression where they are defined. This is a significant improvement over the older var keyword, which is function-scoped (or globally-scoped if declared outside a function), and does not respect block-level scoping.

    Key Features of let:

    • Block Scope: The variable exists only within the nearest enclosing block (e.g., inside an {} pair).
    • No Hoisting Issues: While let declarations are hoisted, they are not initialized until the code defining them is executed. Accessing them before declaration results in a ReferenceError (temporal dead zone).
    • No Redeclaration: The same variable cannot be declared twice in the same scope with let.

    Example:

    let counter = 30;
    if (counter === 30) {
    let counter = 31;
    console.log(counter); // Output: 31 (block-scoped variable inside if-block)
    }
    console.log(counter); // Output: 30 (outer variable, unaffected by inner block)
    

    In this example, the counter inside the if block is a separate variable from the one outside. The let keyword ensures that both have their own distinct scope.

    In summary, you need to use let when you want variables to be limited to the block in which they are defined, preventing accidental overwrites and bugs related to variable scope.

  • Question 19

    What is the difference between let and var

    You can list out the differences in a tabular format

    varlet
    It has been available from the beginning of JavaScriptIntroduced as part of ES6
    It has function scopeIt has block scope
    Variable declaration will be hoisted, initialized as undefinedHoisted but not initialized
    It is possible to re-declare the variable in the same scopeIt is not possible to re-declare the variable

    Let's take an example to see the difference,

    function userDetails(username) {
    if (username) {
    console.log(salary); // undefined due to hoisting
    console.log(age); // ReferenceError: Cannot access 'age' before initialization
    let age = 30;
    var salary = 10000;
    }
    console.log(salary); //10000 (accessible due to function scope)
    console.log(age); //error: age is not defined(due to block scope)
    }
    userDetails("John");
    
  • Question 20

    What is the reason to choose the name let as a keyword

    The keyword let was chosen because it originates from mathematical notation, where "let" is used to introduce new variables (for example, "let x = 5"). This term was adopted by several early programming languages such as Scheme and BASIC, establishing a tradition in computer science. JavaScript follows this convention by using let to declare variables with block scope, providing a modern alternative to var. The choice helps make the language more familiar to programmers coming from other languages and aligns with the mathematical practice of variable assignment.

  • Question 21

    How do you redeclare variables in a switch block without an error

    When you try to redeclare variables using let or const in multiple case clauses of a switch statement, you will get a SyntaxError. This happens because, in JavaScript, all case clauses within a switch statement share the same block scope. For example:

    let counter = 1;
    switch (x) {
    case 0:
    let name;
    break;
    case 1:
    let name; // SyntaxError: Identifier 'name' has already been declared
    break;
    }
    

    To avoid this error, you can create a new block scope within each case clause by wrapping the code in curly braces {}. This way, each let or const declaration is scoped only to that block, and redeclaration errors are avoided:

    let counter = 1;
    switch (x) {
    case 0: {
    let name;
    // code for case 0
    break;
    }
    case 1: {
    let name; // No SyntaxError
    // code for case 1
    break;
    }
    }
    

    That means, to safely redeclare variables in different cases of a switch statement, wrap each case’s code in its own block using curly braces. This ensures each variable declaration is scoped to its specific case block.

  • Question 22

    What is the Temporal Dead Zone

    The Temporal Dead Zone (TDZ) refers to the period between the start of a block and the point where a variable declared with let or const is initialized. During this time, the variable exists in scope but cannot be accessed, and attempting to do so results in a ReferenceError.

    This behavior is part of JavaScript's ES6 (ECMAScript 2015) specification and applies only to variables declared with let and const, not var. Variables declared with var are hoisted and initialized with undefined, so accessing them before the declaration does not throw an error, though it can lead to unexpected results.

    Example

    function someMethod() {
    console.log(counter1); // Output: undefined (due to var hoisting)
    console.log(counter2); // Throws ReferenceError (TDZ for let)
    
    var counter1 = 1;
    let counter2 = 2;
    }
    
  • Question 23

    What is an IIFE (Immediately Invoked Function Expression)

    IIFE (Immediately Invoked Function Expression) is a JavaScript function that runs as soon as it is defined. The signature of it would be as below,

    (function () {
    // logic here
    })();
    

    The primary reason to use an IIFE is to obtain data privacy because any variables declared within the IIFE cannot be accessed by the outside world. i.e, If you try to access variables from the IIFE then it throws an error as below,

    (function () {
    var message = "IIFE";
    console.log(message);
    })();
    console.log(message); //Error: message is not defined
    
  • Question 24

    How do you decode or encode a URL in JavaScript?

    encodeURI() function is used to encode an URL. This function requires a URL string as a parameter and return that encoded string. decodeURI() function is used to decode an URL. This function requires an encoded URL string as parameter and return that decoded string.

    Note: If you want to encode characters such as / ? : @ & = + $ # then you need to use encodeURIComponent().

    let uri = "employeeDetails?name=john&occupation=manager";
    let encoded_uri = encodeURI(uri);
    let decoded_uri = decodeURI(encoded_uri);
    
  • Question 25

    What is memoization

    Memoization is a functional programming technique which attempts to increase a function’s performance by caching its previously computed results. Each time a memoized function is called, its parameters are used to index the cache. If the data is present, then it can be returned, without executing the entire function. Otherwise the function is executed and then the result is added to the cache. Let's take an example of adding function with memoization,

    const memoizeAddition = () => {
    let cache = {};
    return (value) => {
    if (value in cache) {
    console.log("Fetching from cache");
    return cache[value]; // Here, cache.value cannot be used as property name starts with the number which is not a valid JavaScript  identifier. Hence, can only be accessed using the square bracket notation.
    } else {
    console.log("Calculating result");
    let result = value + 20;
    cache[value] = result;
    return result;
    }
    };
    };
    // returned function from memoizeAddition
    const addition = memoizeAddition();
    console.log(addition(20)); //output: 40 calculated
    console.log(addition(20)); //output: 40 cached
    
  • Question 26

    What is Hoisting

    Hoisting is JavaScript's default behavior where variable and function declarations are moved to the top of their scope before code execution. This means you can access certain variables and functions even before they are defined in the code.

    Example of variable hoisting:

    console.log(message); // Output: undefined
    var message = "The variable has been hoisted";
    
    var message;
    console.log(message); // undefined
    message = "The variable has been hoisted";
    

    Example of function hoisting:

    message("Good morning"); // Output: Good morning
    
    function message(name) {
    console.log(name);
    }
    

    Because of hoisting, functions can be used before they are declared.

  • Question 27

    What are classes in ES6

    In ES6, JavaScript classes are primarily syntactic sugar over JavaScript’s existing prototype-based inheritance. For example, the prototype based inheritance written in function expression as below,

    function Bike(model, color) {
    this.model = model;
    this.color = color;
    }
    
    Bike.prototype.getDetails = function () {
    return this.model + " bike has" + this.color + " color";
    };
    

    Whereas ES6 classes can be defined as an alternative

    class Bike {
    constructor(color, model) {
    this.color = color;
    this.model = model;
    }
    
    getDetails() {
    return this.model + " bike has" + this.color + " color";
    }
    }
    
  • Question 28

    What are closures

    A closure is the combination of a function bundled(enclosed) together with its lexical environment within which that function was declared. i.e, It is an inner function that has access to the outer or enclosing function’s variables, functions and other data even after the outer function has finished its execution. The closure has three scope chains.

    1. Own scope where variables defined between its curly brackets
    2. Outer function's variables
    3. Global variables

    Let's take an example of closure concept,

    function Welcome(name) {
    var greetingInfo = function (message) {
    console.log(message + " " + name);
    };
    return greetingInfo;
    }
    var myFunction = Welcome("John");
    myFunction("Welcome "); //Output: Welcome John
    myFunction("Hello Mr."); //output: Hello Mr. John
    

    As per the above code, the inner function(i.e, greetingInfo) has access to the variables in the outer function scope(i.e, Welcome) even after the outer function has returned.

  • Question 29

    What are modules

    Modules refer to small units of independent, reusable code and also act as the foundation of many JavaScript design patterns. Most of the JavaScript modules export an object literal, a function, or a constructor

  • Question 30

    Why do you need modules

    Below are the list of benefits using modules in javascript ecosystem

    1. Maintainability
    2. Reusability
    3. Namespacing
Get LinkedIn Premium at Rs 399