Skip to main content

Frequently Asked JavaScript Questions Part-1

Published 11 min readMarkdown
Frequently Asked JavaScript Questions 
Part-1

Explain the concept of block scope in JavaScript and how it relates to the let and const keywords. Provide examples to demonstrate the difference between var, let, and const in terms of scope and mutability.

Block scope in JavaScript refers to the visibility and accessibility of variables within a block of code, typically defined by curly braces {}. This concept became more prominent with the introduction of let and const in ES6 (ECMAScript 2015).

  1. Block Scope:

    • A block is defined by curly braces {}, such as in if statements, loops, or standalone blocks.

    • Variables declared with let and const are block-scoped, meaning they are only accessible within the block they are declared in.

    • Variables declared with var are function-scoped or globally-scoped, not block-scoped.

    • var vs let vs const: a) Scope

        {
          var x = 1;
          let y = 2;
          const z = 3;
        }
        console.log(x); // 1
        console.log(y); // ReferenceError: y is not defined
        console.log(z); // ReferenceError: z is not defined
      

      var is accessible outside the block, while let and const are not. b) Hoisting:

    •   console.log(a); // undefined
        console.log(b); // ReferenceError: Cannot access 'b' before initialization
        console.log(c); // ReferenceError: Cannot access 'c' before initialization
      
        var a = 1;
        let b = 2;
        const c = 3;
      

      var is hoisted and initialized with undefined, while let and const are hoisted but not initialized (temporal dead zone). c) Re-declaration:

    •   var x = 1;
        var x = 2; // Allowed
      
        let y = 1;
        let y = 2; // SyntaxError: Identifier 'y' has already been declared
      
        const z = 1;
        const z = 2; // SyntaxError: Identifier 'z' has already been declared
      

var allows re-declaration, let and const do not. d) Mutability:

  1.  var a = 1;
     let b = 2;
     const c = 3;
    
     a = 4; // Allowed
     b = 5; // Allowed
     c = 6; // TypeError: Assignment to a constant variable
    
     const obj = { key: 'value' };
     obj.key = 'new value'; // Allowed
     obj = {}; // TypeError: Assignment to a constant variable
    

    var and let allow reassignment, const does not. However, for objects and arrays, const only prevents reassignment of the variable itself, not modification of its contents.

In summary, let and const provide block scoping, which offers better control over variable visibility and helps prevent unintended side effects. const adds an extra layer of immutability for the variable binding. These features make code more predictable and easier to reason about, which is why they are generally preferred over var in modern JavaScript development.

Explain the concept of module scope in JavaScript. How does it differ from global and function scopes? Provide examples of how to use module scope with both CommonJS and ES6 module systems.

Module scope in JavaScript encapsulates variables and functions within a module, making them inaccessible from outside unless explicitly exported. It differs from global scope (accessible everywhere) and function scope (limited to a function). Module scope helps prevent naming conflicts and global scope pollution.

In CommonJS (Node.js):

const privateVar = 'private';
module.exports = { publicFunction: () => console.log(privateVar) };

In ES6 modules:

const privateVar = 'private';
export const publicFunction = () => console.log(privateVar);

What is the global object in JavaScript? How does it differ across environments, and what are some key properties and methods associated with it?

The global object in JavaScript is the top-level object in the global scope. Its key aspects include:

  1. In browsers, it's window. In Node.js, it's global. In strict mode, it's undefined.

  2. ES2020 introduced globalThis, which provides a standard way to access the global object across environments.

  3. Key properties/methods: setTimeout(), console, undefined, NaN, Infinity.

  4. Global variables become properties of the global object:

  5.  var x = 10;
     console.log(window.x); // 10 (in browsers)
    
  6. It hosts built-in object constructors like Object, Array, String, etc.

  7. Avoid polluting it to prevent naming conflicts and maintain clean code.

    Explain function scope and lexical environment in JavaScript. How do they relate to each other?

  1. Function Scope:

    • Variables declared inside a function are only accessible within that function.

    • Each function creates its own scope.

  2. Lexical Environment:

    • It's the internal JavaScript engine construct that holds identifier-variable mapping.

    • Consists of the environment record (variable and function declarations) and a reference to the outer environment.

  3. Relationship:

    • When a function is created, it captures its lexical environment.

    • This allows for closures, where inner functions can access variables from their outer function's scope.

  4. Example:

     javascriptCopyfunction outer() {
       let x = 10;
       function inner() {
         console.log(x); // Accesses x from outer's lexical environment
       }
       return inner;
     }
     let closureFn = outer();
     closureFn(); // Outputs: 10
    
  5. Scope Chain:

    • When resolving variables, JavaScript looks up the chain of lexical environments.

This mechanism enables powerful patterns like module patterns and data privacy in JavaScript.

What is hoisting in JavaScript? How does it differ for var, let, and const declarations, and for function declarations vs. function expressions?

Hoisting is JavaScript's behavior of moving declarations to the top of their respective scopes during the compilation phase, before code execution.

  1. Variable hoisting:

    • var: Hoisted and initialized with undefined

    • let and const: Hoisted but not initialized (Temporal Dead Zone)

    javascriptCopyconsole.log(a); // undefined
    console.log(b); // ReferenceError
    var a = 1;
    let b = 2;
  1. Function hoisting:

    • Function declarations are fully hoisted

    • Function expressions are not hoisted

    javascriptCopyfoo(); // "Hello"
    bar(); // TypeError: bar is not a function

    function foo() { console.log("Hello"); }
    var bar = function() { console.log("World"); };
  1. Key points:

    • Hoisting doesn't physically move code; it's conceptual

    • Best practice: Declare variables at the top of their scope

    • Use let and const to avoid hoisting-related bugs

Remember, while hoisting exists, relying on it can lead to confusing code. It's better to explicitly declare variables and functions before using them.

What are closures in JavaScript? Provide some practical, real-world examples of how closures are used in modern web development.

Closures occur when a function is able to remember and access its lexical scope even when that function is executing outside its original scope. Here are some practical examples:

  1. Data Privacy / Module Pattern:

     javascriptCopyfunction createCounter() {
       let count = 0;
       return {
         increment: () => ++count,
         decrement: () => --count,
         getCount: () => count
       };
     }
    
     const counter = createCounter();
     console.log(counter.getCount()); // 0
     counter.increment();
     console.log(counter.getCount()); // 1
    

    This pattern is used to create private variables in JavaScript, mimicking class-like behavior.

  2. Function Factories:

     javascriptCopyfunction multiplier(factor) {
       return function(x) {
         return x * factor;
       };
     }
    
     const double = multiplier(2);
     const triple = multiplier(3);
    
     console.log(double(5)); // 10
     console.log(triple(5)); // 15
    

    This is useful for creating specialized functions from more general ones.

  3. Callbacks in Asynchronous Operations:

     javascriptCopyfunction fetchData(url) {
       return new Promise((resolve, reject) => {
         // Simulating async operation
         setTimeout(() => {
           const data = { id: 1, name: 'John' };
           resolve(data);
         }, 1000);
       });
     }
    
     fetchData('api/users').then(data => {
       console.log(data.name); // 'John'
     });
    

    The callback passed to then forms a closure, remembering the data parameter.

  4. Event Handlers:

     javascriptCopyfunction setupButton(label) {
       const button = document.createElement('button');
       button.textContent = label;
       button.addEventListener('click', () => {
         console.log(`${label} was clicked`);
       });
       return button;
     }
    
     const btn = setupButton('Click me');
     document.body.appendChild(btn);
    

    The event listener callback forms a closure, remembering the label parameter.

  5. Memoization (Caching):

     javascriptCopyfunction memoize(fn) {
       const cache = new Map();
       return function(...args) {
         const key = JSON.stringify(args);
         if (cache.has(key)) {
           return cache.get(key);
         }
         const result = fn.apply(this, args);
         cache.set(key, result);
         return result;
       };
     }
    
     const expensiveOperation = memoize((n) => {
       console.log('Calculating...');
       return n * 2;
     });
    
     console.log(expensiveOperation(5)); // Logs: Calculating... 10
     console.log(expensiveOperation(5)); // Logs: 10 (cached)
    

    This uses closures to implement a caching mechanism for expensive operations.

These examples demonstrate how closures are fundamental to many JavaScript patterns and features, from data privacy to event handling and performance optimization.

What is an IIFE in JavaScript? Explain its syntax and provide examples of its practical uses.

An IIFE (Immediately Invoked Function Expression) is a JavaScript function that runs as soon as it is defined. Its syntax and key points are:

  1. Basic syntax:

     javascriptCopy(function() {
       // code here
     })();
    
  2. With parameters:

     javascriptCopy(function(name) {
       console.log('Hello, ' + name);
     })('John');
    
  3. Main uses: a. Creating private scope:

     javascriptCopyconst counter = (function() {
       let count = 0;
       return {
         increment: () => ++count,
         getCount: () => count
       };
     })();
    

    b. Avoiding global namespace pollution:

     javascriptCopy(function($) {
       // jQuery plugin code
     })(jQuery);
    
  4. ES6 arrow function version:

     javascriptCopy(() => {
       // code here
     })();
    
  5. Benefits:

    • Encapsulates variables

    • Doesn't pollute the global scope

    • Can be used to create modules

IIFEs are less common in modern JavaScript due to block-scoped declarations (let, const) and ES6 modules, but understanding them is crucial for maintaining legacy code and certain design patterns.

What is currying in JavaScript? Provide an example and explain its practical applications.

Currying is a technique of transforming a function that takes multiple arguments into a sequence of functions, each taking a single argument.

  1. Basic example:

     javascriptCopy// Non-curried function
     function add(a, b) {
       return a + b;
     }
    
     // Curried version
     function curriedAdd(a) {
       return function(b) {
         return a + b;
       };
     }
    
     console.log(add(2, 3));        // 5
     console.log(curriedAdd(2)(3)); // 5
    
  2. ES6 arrow function syntax:

     javascriptCopyconst curriedAdd = a => b => a + b;
    
  3. Practical applications: a. Partial application:

     javascriptCopyconst addFive = curriedAdd(5);
     console.log(addFive(3)); // 8
    

    b. Function composition:

     javascriptCopyconst compose = (f, g) => x => f(g(x));
     const double = x => x * 2;
     const addOne = x => x + 1;
     const doubleAndAddOne = compose(addOne, double);
     console.log(doubleAndAddOne(3)); // 7
    

    c. Creating specialized functions:

     javascriptCopyconst multiply = a => b => a * b;
     const double = multiply(2);
     const triple = multiply(3);
     console.log(double(4)); // 8
     console.log(triple(4)); // 12
    
  4. Benefits:

    • Increases code reusability

    • Enables function composition

    • Allows for more flexible function calls

  5. Drawbacks:

    • Can make code harder to read if overused

    • Might introduce performance overhead for simple functions

Currying is particularly useful in functional programming paradigms and when working with higher-order functions.

Explain how object references work in JavaScript. How does this affect the way objects are copied and compared?

In JavaScript, objects are referenced by memory address, not by value. This has several important implications:

  1. Object assignment creates a reference:

     javascriptCopylet obj1 = {a: 1};
     let obj2 = obj1;
     obj2.a = 2;
     console.log(obj1.a); // 2
    
  2. Comparison of objects:

     javascriptCopylet obj1 = {a: 1};
     let obj2 = {a: 1};
     console.log(obj1 === obj2); // false
     console.log(obj1 == obj2);  // false
    
  3. Shallow copy vs Deep copy:

     javascriptCopy// Shallow copy
     let original = {a: 1, b: {c: 2}};
     let shallowCopy = Object.assign({}, original);
     original.b.c = 3;
     console.log(shallowCopy.b.c); // 3
    
     // Deep copy
     let deepCopy = JSON.parse(JSON.stringify(original));
     original.b.c = 4;
     console.log(deepCopy.b.c); // 3
    
  4. Function parameters:

     javascriptCopyfunction changeObj(obj) {
       obj.a = 2;
     }
     let myObj = {a: 1};
     changeObj(myObj);
     console.log(myObj.a); // 2
    
  5. Key points:

    • Primitives are passed by value

    • Objects are passed by reference

    • Equality operators compare references for objects, not contents

    • Modifying an object affects all references to it

Understanding object references is crucial for avoiding unintended side effects and properly manipulating complex data structures in JavaScript.

What are shallow copy and deep copy in JavaScript? Provide examples of how to perform each and explain when you would use one over the other.

Answer: Shallow copy and deep copy are two ways of copying objects in JavaScript, each with different implications for nested objects.

  1. Shallow Copy:

    • Copies the top-level properties but nested objects are still referenced.

    • Methods: a. Object.assign():

        javascriptCopylet original = { a: 1, b: { c: 2 } };
        let shallowCopy = Object.assign({}, original);
      

      b. Spread operator:

        javascriptCopylet shallowCopy = { ...original };
      
  2. Deep Copy:

    • Creates a new copy of all nested objects recursively.

    • Methods: a. JSON parse/stringify (with limitations):

        javascriptCopylet deepCopy = JSON.parse(JSON.stringify(original));
      

      b. Custom recursive function:

        javascriptCopyfunction deepCopy(obj) {
          if (typeof obj !== 'object' || obj === null) return obj;
          let copy = Array.isArray(obj) ? [] : {};
          for (let key in obj) {
            copy[key] = deepCopy(obj[key]);
          }
          return copy;
        }
      
  3. Comparison:

     javascriptCopyoriginal.b.c = 3;
     console.log(shallowCopy.b.c); // 3
     console.log(deepCopy.b.c);    // 2
    
  4. When to use:

    • Shallow copy: When you only need to copy top-level properties or when dealing with simple objects.

    • Deep copy: When you need a completely independent copy, including all nested objects.

  5. Considerations:

    • Performance: Shallow copy is faster but may lead to unintended side effects.

    • Complexity: Deep copy ensures complete independence but can be overkill for simple objects.

    • Limitations: JSON method doesn't work for functions, undefined, or circular references.

Understanding these concepts is crucial for managing complex data structures and avoiding unintended mutations in your JavaScript applications.

Explain the this keyword in JavaScript. How does its value change in different contexts, and how do arrow functions affect it? Also, describe the difference between method invocation and function invocation.

  1. The this keyword:

    • Refers to the execution context of a function

    • Its value depends on how the function is called

  2. this in different contexts: a. Global context: refers to the global object (window in browsers, global in Node.js) b. Function context: depends on how the function is called c. Method context: refers to the object the method is called on d. Constructor context: refers to the newly created instance

  3. Examples:

     javascriptCopyconsole.log(this); // global object
    
     function regularFunc() {
       console.log(this); // global object (in non-strict mode)
     }
    
     let obj = {
       method: function() {
         console.log(this); // obj
       }
     };
    
     function Constructor() {
       console.log(this); // newly created instance
     }
    
  4. Arrow functions and this:

    • Arrow functions don't have their own this

    • They inherit this from the enclosing scope

    javascriptCopylet obj = {
      method: function() {
        setTimeout(() => {
          console.log(this); // obj
        }, 100);
      }
    };
  1. Method invocation vs Function invocation:

    • Method invocation: object.method()

      • this refers to the object
    • Function invocation: function()

      • this refers to global object (non-strict) or undefined (strict)
  2. Binding this:

    • call(), apply(), bind() can explicitly set this
    javascriptCopyfunction greet() {
      console.log(`Hello, ${this.name}`);
    }
    greet.call({name: 'John'}); // "Hello, John"
  1. Common pitfalls:

    • Losing this context in callbacks

    • this in nested functions

Understanding this is crucial for working with object-oriented patterns and handling context in JavaScript functions and methods.

No comments yet. Be the first to comment.