FrontendDeveloper.in

JavaScript Interview Questions

  • Question 436

    What is function execution context?

    Whenever a function is invoked, the JavaScript engine creates a different type of Execution Context known as a Function Execution Context (FEC) within the Global Execution Context (GEC) to evaluate and execute the code within that function.

  • Question 437

    What is debouncing?

    Debouncing is a programming technique used to limit how often a function is executed. Specifically, it ensures that a function is only triggered after a certain amount of time has passed since it was last invoked. This prevents unnecessary or excessive function calls, which can help optimize performance and reduce unnecessary CPU usage or API requests.

    For example, when a user types in a search box, you typically want to wait until they’ve finished typing before fetching suggestions. Without debouncing, an API call would be triggered on every keystroke, potentially causing performance issues. With debouncing, the function call is postponed until the user stops typing for a specified period (e.g., 300ms). If the user types again before this time elapses, the timer resets.

    Typical use cases for debouncing include:

    • Search box suggestions (wait until typing pauses before fetching results)
    • Auto-saving text fields (save only after the user stops typing)
    • Preventing double-clicks on buttons
    • Handling window resize or scroll events efficiently

    Example Debounce Function:

    JavaScript

    function debounce(func, timeout = 500) {
    let timer;
    return function (...args) {
    clearTimeout(timer);
    timer = setTimeout(() => {
    func.apply(this, args);
    }, timeout);
    };
    }
    

    Usage Example:

    JavaScript

    function fetchResults() {
    console.log("Fetching input suggestions");
    }
    const processChange = debounce(fetchResults, 300);
    
    // Attach to input element
    <input type="text" onkeyup="processChange()" />
    
    // Attach to button
    <button onclick="processChange()">Click me</button>
    
    // Attach to window event
    window.addEventListener("scroll", processChange);
    

    How it works: When processChange is invoked (e.g., by typing or clicking), any pending execution is canceled, and the function is scheduled to run after the specified delay. If another event occurs before the delay is up, the timer resets, and the function will only run after events have stopped for the delay duration.

    Debouncing is an essential tool for improving user experience and application performance, especially when dealing with events that can fire rapidly and repeatedly.

  • Question 438

    What is throttling?

    Throttling is a programming technique used to control the rate at which a function is executed. When an event is triggered continuously—such as during window resizing, scrolling, or mouse movement—throttling ensures that the associated event handler is not called more often than a specified interval. This helps improve performance by reducing the number of expensive function calls and preventing performance bottlenecks.

    Common use cases:

    • Window resize events
    • Scroll events
    • Mouse movement or drag events
    • API rate limiting

    How does throttling work? Throttling will execute the function at most once every specified time interval, ignoring additional calls until the interval has passed.

    Example: Throttle Implementation and Usage

    JavaScript

    // Simple throttle function: allows 'func' to run at most once every 'limit' ms
    function throttle(func, limit) {
    let inThrottle = false;
    return function(...args) {
    if (!inThrottle) {
    func.apply(this, args);
    inThrottle = true;
    setTimeout(() => (inThrottle = false), limit);
    }
    };
    }
    
    // Usage: throttling a scroll event handler
    function handleScrollAnimation() {
    console.log('Scroll event triggered');
    }
    
    window.addEventListener(
    "scroll",
    throttle(handleScrollAnimation, 100) // Will run at most once every 100ms
    );
    
  • Question 439

    What is optional chaining?

    According to MDN official docs, the optional chaining operator (?.) permits reading the value of a property located deep within a chain of connected objects without having to expressly validate that each reference in the chain is valid.

    The ?. operator is like the . chaining operator, except that instead of causing an error if a reference is nullish (null or undefined), the expression short-circuits with a return value of undefined. When used with function calls, it returns undefined if the given function does not exist.

    const adventurer = {
    name: "Alice",
    cat: {
    name: "Dinah",
    },
    };
    
    const dogName = adventurer.dog?.name;
    console.log(dogName);
    // expected output: undefined
    
    console.log(adventurer.someNonExistentMethod?.());
    // expected output: undefined
    
  • Question 440

    What is an environment record?

    According to ECMAScript specification 262 (9.1):

    Environment Record is a specification type used to define the association of Identifiers to specific variables and functions, based upon the lexical nesting structure of ECMAScript code.

    Usually an Environment Record is associated with some specific syntactic structure of ECMAScript code such as a FunctionDeclaration, a BlockStatement, or a Catch clause of a TryStatement.

    Each time such code is evaluated, a new Environment Record is created to record the identifier bindings that are created by that code.

  • Question 441

    How to verify if a variable is an array?

    It is possible to check if a variable is an array instance using 3 different ways,

    1. Array.isArray() method:

    The Array.isArray(value) utility function is used to determine whether value is an array or not. This function returns a true boolean value if the variable is an array and a false value if it is not.

    const numbers = [1, 2, 3];
    const user = { name: "John" };
    Array.isArray(numbers); // true
    Array.isArray(user); //false
    
    1. instanceof operator:

    The instanceof operator is used to check the type of an array at run time. It returns true if the type of a variable is an Array other false for other type.

    const numbers = [1, 2, 3];
    const user = { name: "John" };
    console.log(numbers instanceof Array); // true
    console.log(user instanceof Array); // false
    
    1. Checking constructor type:

    The constructor property of the variable is used to determine whether the variable Array type or not.

    const numbers = [1, 2, 3];
    const user = { name: "John" };
    console.log(numbers.constructor === Array); // true
    console.log(user.constructor === Array); // false
    
  • Question 442

    What is pass by value and pass by reference?

    Pass-by-value creates a new space in memory and makes a copy of a value. Primitives such as string, number, boolean etc will actually create a new copy. Hence, updating one value doesn't impact the other value. i.e, The values are independent of each other.

    let a = 5;
    let b = a;
    
    b++;
    console.log(a, b); //5, 6
    

    In the above code snippet, the value of a is assigned to b and the variable b has been incremented. Since there is a new space created for variable b, any update on this variable doesn't impact the variable a.

    Pass by reference doesn't create a new space in memory but the new variable adopts a memory address of an initial variable. Non-primitives such as objects, arrays and functions gets the reference of the initiable variable. i.e, updating one value will impact the other variable.

    let user1 = {
    name: "John",
    age: 27,
    };
    let user2 = user1;
    user2.age = 30;
    
    console.log(user1.age, user2.age); // 30, 30
    

    In the above code snippet, updating the age property of one object will impact the other property due to the same reference.

  • Question 443

    What are the differences between primitives and non-primitives?

    JavaScript language has both primitives and non-primitives but there are few differences between them as below,

    PrimitivesNon-primitives
    These types are predefinedCreated by developer
    These are immutableMutable
    Compare by valueCompare by reference
    Stored in StackStored in heap
    Contain certain valueCan contain NULL too
  • Question 444

    How do you create your own bind method using either call or apply method?

    The custom bind function needs to be created on Function prototype inorder to use it as other builtin functions. This custom function should return a function similar to original bind method and the implementation of inner function needs to use apply method call.

    The function which is going to bind using custom myOwnBind method act as the attached function(boundTargetFunction) and argument as the object for apply method call.

    Function.prototype.myOwnBind = function (whoIsCallingMe) {
    if (typeof this !== "function") {
    throw new Error(this + "cannot be bound as it's not callable");
    }
    const boundTargetFunction = this;
    return function () {
    boundTargetFunction.apply(whoIsCallingMe, arguments);
    };
    };
    
  • Question 445

    What are the differences between pure and impure functions?

    Some of the major differences between pure and impure function are as below,

    Pure functionImpure function
    It has no side effectsIt causes side effects
    It is always return the same resultIt returns different result on each call
    Easy to read and debugDifficult to read and debug because they are affected by external code
  • Question 446

    What is referential transparency?

    An expression in javascript that can be replaced by its value without affecting the behaviour of the program is called referential transparency. Pure functions are referentially transparent.

    const add = (x, y) => x + y;
    const multiplyBy2 = (x) => x * 2;
    
    //Now add (2, 3) can be replaced by 5.
    
    multiplyBy2(add(2, 3));
    
  • Question 447

    What are the possible side-effects in javascript?

    A side effect is the modification of the state through the invocation of a function or expression. These side effects make our function impure by default. Below are some side effects which make function impure,

    • Making an HTTP request. Asynchronous functions such as fetch and promise are impure.
    • DOM manipulations
    • Mutating the input data
    • Printing to a screen or console: For example, console.log() and alert()
    • Fetching the current time
    • Math.random() calls: Modifies the internal state of Math object
  • Question 448

    What are compose and pipe functions?

    The "compose" and "pipe" are two techniques commonly used in functional programming to simplify complex operations and make code more readable. They are not native to JavaScript and higher-order functions. the compose() applies right to left any number of functions to the output of the previous function.

  • Question 449

    What is module pattern?

    Module pattern is a designed pattern used to wrap a set of variables and functions together in a single scope returned as an object. JavaScript doesn't have access specifiers similar to other languages(Java, Python, etc) to provide private scope. It uses IIFE (Immediately invoked function expression) to allow for private scopes. i.e., a closure that protect variables and methods.

    The module pattern looks like below,

    (function () {
    // Private variables or functions goes here.
    
    return {
    // Return public variables or functions here.
    };
    })();
    

    Let's see an example of a module pattern for an employee with private and public access,

    const createEmployee = (function () {
    // Private
    const name = "John";
    const department = "Sales";
    const getEmployeeName = () => name;
    const getDepartmentName = () => department;
    
    // Public
    return {
    name,
    department,
    getName: () => getEmployeeName(),
    getDepartment: () => getDepartmentName(),
    };
    })();
    
    console.log(createEmployee.name);
    console.log(createEmployee.department);
    console.log(createEmployee.getName());
    console.log(createEmployee.getDepartment());
    

    Note: It mimic the concepts of classes with private variables and methods.

  • Question 450

    What is Function Composition?

    It is an approach where the result of one function is passed on to the next function, which is passed to another until the final function is executed for the final result.

    //example
    const double = (x) => x * 2;
    const square = (x) => x * x;
    
    var output1 = double(2);
    var output2 = square(output1);
    console.log(output2);
    
    var output_final = square(double(2));
    console.log(output_final);
    
Get LinkedIn Premium at Rs 399