JavaScript Interview Questions and Answers | Comprehensive Prep Guide

Chandan kumarChandan kumar
35 min read

1. Data Types (10 Questions)

1. What are the primitive data types in JavaScript?

The primitive data types in JavaScript are:

  1. String: Represents textual data.

      let str = "Hello, World!";
    
  2. Number: Represents numeric values, both integers and floats.

     let num = 42;
    
  3. Boolean: Represents true or false values.

     let isActive = true;
    
  4. BigInt: Represents integers of arbitrary length.

     let bigInt = 1234567890123456789012345678901234567890n;
    
  5. Symbol: Represents unique and immutable values.

     let sym = Symbol("uniqueKey");
    
  6. null: Represents an intentional absence of value.

     let empty = null;
    
  7. undefined: Represents a variable that has been declared but not assigned a value.

     let unassigned;
    

2. What is the difference between null and undefined?

  • null:

    • Explicitly assigned by the programmer to indicate "no value."

    • Type is object (a known quirk in JavaScript).

    let value = null;
    console.log(value); // Output: null
    console.log(typeof value); // Output: object
  • undefined:

    • A variable is declared but not assigned a value.

    • Type is undefined.

    let value;
    console.log(value); // Output: undefined
    console.log(typeof value); // Output: undefined

3. How do you check the type of a variable in JavaScript?

You can use the typeof operator:

let num = 42;
console.log(typeof num); // Output: number

let str = "Hello";
console.log(typeof str); // Output: string

let obj = { key: "value" };
console.log(typeof obj); // Output: object

4. What is NaN in JavaScript, and how do you check if a value is NaN?

  • NaN: Stands for "Not a Number." It is a special value that indicates a numeric operation has failed to produce a valid number.

  • You can check for NaN using Number.isNaN():

console.log(Number("abc")); // Output: NaN
console.log(Number.isNaN(Number("abc"))); // Output: true

5. What are Symbol and BigInt in JavaScript? Provide examples.

  • Symbol: Represents a unique identifier.

      let sym1 = Symbol("id");
      let sym2 = Symbol("id");
      console.log(sym1 === sym2); // Output: false (Symbols are always unique)
    
  • BigInt: Represents numbers larger than the safe limit for Number.

      let bigInt = 1234567890123456789012345678901234567890n;
      console.log(bigInt + 1n); // Output: 1234567890123456789012345678901234567891n
    

6. What are falsy values in JavaScript? List them.

The following values are considered falsy in JavaScript:

  1. false

  2. 0 (the number zero)

  3. "" or '' (empty strings)

  4. null

  5. undefined

  6. NaN

Example:

if (0) {
  console.log("This won't execute");
} else {
  console.log("Falsy value"); // Output: Falsy value
}

7. Explain the difference between == and ===.

  • == (Equality):

    • Performs type coercion before comparison.
    console.log(5 == "5"); // Output: true (string "5" is converted to number)
  • === (Strict Equality):

    • Compares both value and type without type coercion.
    console.log(5 === "5"); // Output: false (different types)

8. What is type coercion? Provide examples.

Type coercion is the automatic or implicit conversion of values from one type to another.

Examples:

console.log("5" + 5); // Output: "55" (Number is coerced to String)
console.log("5" - 5); // Output: 0 (String is coerced to Number)
console.log(true + 1); // Output: 2 (Boolean true is coerced to Number 1)

9. How do you convert a number to a string and vice versa in JavaScript?

  • Convert a Number to a String:

      let num = 42;
      console.log(num.toString()); // Output: "42"
      console.log(String(num));    // Output: "42"
    
  • Convert a String to a Number:

      let str = "42";
      console.log(Number(str));    // Output: 42
      console.log(parseInt(str));  // Output: 42
    

10. What is the difference between typeof and instanceof?

  • typeof:

    • Returns the data type as a string.

    • Works with both primitives and objects but is limited in distinguishing objects.

    console.log(typeof 42); // Output: "number"
    console.log(typeof {}); // Output: "object"
  • instanceof:

    • Checks if an object is an instance of a specific constructor or class.
    let arr = [];
    console.log(arr instanceof Array); // Output: true
    console.log(arr instanceof Object); // Output: true

2. Functions (10 Questions)

11. What is the difference between function declarations and function expressions?

  • Function Declaration:

    • Named function.

    • Hoisted, meaning it can be called before it is defined.

    console.log(sum(3, 4)); // Output: 7
    function sum(a, b) {
      return a + b;
    }
  • Function Expression:

    • Can be anonymous or named.

    • Not hoisted, so it cannot be used before its definition.

    console.log(multiply(3, 4)); // Error: multiply is not defined
    const multiply = function (a, b) {
      return a * b;
    };

12. What is a first-class function in JavaScript?

A first-class function is a function that can:

  • Be assigned to variables.

  • Be passed as arguments to other functions.

  • Be returned from other functions.

Example:

const greet = function (name) {
  return `Hello, ${name}!`;
};

function executeFunction(fn, value) {
  console.log(fn(value));
}

executeFunction(greet, "John"); // Output: Hello, John!

13. What are arrow functions, and how are they different from regular functions?

  • Arrow Functions:

    • Shorter syntax for writing functions.

    • Do not have their own this or arguments.

    const add = (a, b) => a + b;
    console.log(add(5, 7)); // Output: 12
  • Differences:

    • Arrow functions inherit this from the surrounding lexical scope.
    function RegularFunction() {
      this.name = "Regular";
      setTimeout(function () {
        console.log(this.name); // undefined
      }, 1000);
    }

    function ArrowFunction() {
      this.name = "Arrow";
      setTimeout(() => {
        console.log(this.name); // Output: Arrow
      }, 1000);
    }

    new RegularFunction();
    new ArrowFunction();

14. Explain the concept of closures with an example.

A closure is a function that "remembers" the variables from its outer scope, even after the outer function has executed.

Example:

function outer() {
  let count = 0;
  return function inner() {
    count++;
    console.log(count);
  };
}

const counter = outer();
counter(); // Output: 1
counter(); // Output: 2

Here, inner retains access to count from outer's scope.


15. What is the this keyword, and how does it behave in different contexts?

  • this refers to the object that is executing the current function.

  • Behavior:

    1. Global Scope: Refers to window in browsers or global in Node.js.

       console.log(this); // window (in browsers)
      
    2. Object Methods: Refers to the object that owns the method.

       const obj = {
         name: "Object",
         greet: function () {
           console.log(this.name);
         },
       };
       obj.greet(); // Output: Object
      
    3. Arrow Functions: Inherits this from the surrounding context.

       const obj = {
         name: "Arrow",
         greet: () => {
           console.log(this.name);
         },
       };
       obj.greet(); // Output: undefined
      

16. What are higher-order functions? Provide an example.

A higher-order function is a function that:

  1. Takes one or more functions as arguments.

  2. Returns a function as its result.

Example:

function higherOrder(fn) {
  return function (x) {
    return fn(x) * 2;
  };
}

function square(n) {
  return n * n;
}

const doubleSquare = higherOrder(square);
console.log(doubleSquare(3)); // Output: 18

17. Explain the concept of currying in JavaScript.

Currying transforms a function with multiple arguments into a series of nested functions, each taking one argument.

Example:

function add(a) {
  return function (b) {
    return function (c) {
      return a + b + c;
    };
  };
}

console.log(add(1)(2)(3)); // Output: 6

18. What is a pure function in functional programming?

A pure function:

  • Always produces the same output for the same input.

  • Has no side effects (does not modify external variables or states).

Example:

function pureAdd(a, b) {
  return a + b;
}

console.log(pureAdd(2, 3)); // Output: 5

Non-pure function (with side effects):

let total = 0;
function impureAdd(a) {
  total += a;
  return total;
}

19. How do you create a function that takes a variable number of arguments in JavaScript?

You can use the rest operator (...args):

function sum(...args) {
  return args.reduce((acc, val) => acc + val, 0);
}

console.log(sum(1, 2, 3, 4)); // Output: 10

20. Explain the difference between call(), apply(), and bind() with examples.

  1. call():

    • Invokes a function, specifying this and arguments individually.
    function greet(greeting, name) {
      console.log(`${greeting}, ${name}!`);
    }

    greet.call(null, "Hello", "John"); // Output: Hello, John!
  1. apply():

    • Invokes a function, specifying this and arguments as an array.
    greet.apply(null, ["Hi", "Jane"]); // Output: Hi, Jane!
  1. bind():

    • Returns a new function with a specified this and arguments.
    const greetJohn = greet.bind(null, "Welcome", "John");
    greetJohn(); // Output: Welcome, John!

Key Differences:

  • call and apply invoke the function immediately.

  • bind returns a new function that can be called later.


3. Objects (10 Questions)

21. How do you create an object in JavaScript?

You can create objects using various methods:

  1. Object Literal:

     const obj = { name: "John", age: 30 };
    
  2. Constructor Function:

     function Person(name, age) {
       this.name = name;
       this.age = age;
     }
     const person = new Person("John", 30);
    
  3. Object.create():

     const proto = { greet: () => "Hello" };
     const obj = Object.create(proto);
     obj.name = "John";
    

22. What is the difference between Object.keys() and Object.values()?

  • Object.keys(): Returns an array of an object's property names.

  • Object.values(): Returns an array of an object's property values.

Example:

const obj = { name: "John", age: 30 };
console.log(Object.keys(obj));   // Output: ["name", "age"]
console.log(Object.values(obj)); // Output: ["John", 30]

  • A prototype is an object from which other objects inherit properties and methods.

  • Every JavaScript object has an internal [[Prototype]] property that links to another object (or null).

Example:

function Person(name) {
  this.name = name;
}

Person.prototype.greet = function () {
  return `Hello, ${this.name}`;
};

const john = new Person("John");
console.log(john.greet()); // Output: Hello, John

Here, greet is inherited from the Person.prototype.


24. Explain the difference between shallow copy and deep copy with examples.

  • Shallow Copy: Copies only the top-level properties; nested objects are still referenced.

      const obj = { a: 1, b: { c: 2 } };
      const shallowCopy = { ...obj };
      shallowCopy.b.c = 42;
      console.log(obj.b.c); // Output: 42 (nested object is shared)
    
  • Deep Copy: Copies all levels of the object, including nested objects.

      const obj = { a: 1, b: { c: 2 } };
      const deepCopy = JSON.parse(JSON.stringify(obj));
      deepCopy.b.c = 42;
      console.log(obj.b.c); // Output: 2 (nested object is not shared)
    

25. What are getters and setters in JavaScript?

  • Getters: Allow you to define a method to retrieve a property.

  • Setters: Allow you to define a method to set a property.

Example:

const person = {
  firstName: "John",
  lastName: "Doe",
  get fullName() {
    return `${this.firstName} ${this.lastName}`;
  },
  set fullName(name) {
    [this.firstName, this.lastName] = name.split(" ");
  },
};

console.log(person.fullName); // Output: John Doe
person.fullName = "Jane Smith";
console.log(person.firstName); // Output: Jane

26. How can you merge two objects in JavaScript?

You can merge objects using:

  1. Object.assign():

     const obj1 = { a: 1 };
     const obj2 = { b: 2 };
     const merged = Object.assign({}, obj1, obj2);
     console.log(merged); // Output: { a: 1, b: 2 }
    
  2. Spread Operator:

     const merged = { ...obj1, ...obj2 };
     console.log(merged); // Output: { a: 1, b: 2 }
    

27. How do you freeze or seal an object in JavaScript?

  • Object.freeze():

    • Prevents modification of properties or addition of new properties.
    const obj = { a: 1 };
    Object.freeze(obj);
    obj.a = 2; // No effect
    console.log(obj.a); // Output: 1
  • Object.seal():

    • Prevents addition or removal of properties but allows modification of existing properties.
    const obj = { a: 1 };
    Object.seal(obj);
    obj.a = 2; // Allowed
    delete obj.a; // Not allowed
    console.log(obj); // Output: { a: 2 }

28. What is the difference between in and hasOwnProperty() when checking for a property in an object?

  • in: Checks for properties in the object or its prototype chain.

      const obj = { a: 1 };
      console.log("a" in obj); // Output: true
      console.log("toString" in obj); // Output: true (inherited from prototype)
    
  • hasOwnProperty(): Checks only the object's own properties.

      console.log(obj.hasOwnProperty("a")); // Output: true
      console.log(obj.hasOwnProperty("toString")); // Output: false
    

29. Explain the concept of object destructuring with an example.

Object destructuring allows you to extract properties from an object into variables.

Example:

const obj = { name: "John", age: 30 };
const { name, age } = obj;
console.log(name); // Output: John
console.log(age);  // Output: 30

You can also assign default values:

const { city = "Unknown" } = obj;
console.log(city); // Output: Unknown

30. What is the difference between a factory function and a constructor function?

  • Factory Function:

    • A regular function that returns an object.

    • Does not require new keyword.

    function createPerson(name, age) {
      return {
        name,
        age,
        greet() {
          return `Hello, ${name}`;
        },
      };
    }
    const person = createPerson("John", 30);
    console.log(person.greet()); // Output: Hello, John
  • Constructor Function:

    • Uses the new keyword to create objects.

    • Sets this to the new object being created.

    function Person(name, age) {
      this.name = name;
      this.age = age;
      this.greet = function () {
        return `Hello, ${this.name}`;
      };
    }
    const person = new Person("John", 30);
    console.log(person.greet()); // Output: Hello, John

4. Arrays (10 Questions)

31. How do you add and remove elements from an array?

  • Add Elements:

    1. push(): Adds elements to the end of an array.

       let arr = [1, 2, 3];
       arr.push(4);
       console.log(arr); // Output: [1, 2, 3, 4]
      
    2. unshift(): Adds elements to the beginning of an array.

       arr.unshift(0);
       console.log(arr); // Output: [0, 1, 2, 3, 4]
      
  • Remove Elements:

    1. pop(): Removes the last element.

       arr.pop();
       console.log(arr); // Output: [0, 1, 2, 3]
      
    2. shift(): Removes the first element.

       arr.shift();
       console.log(arr); // Output: [1, 2, 3]
      
    3. splice(): Removes elements from a specific position.

       arr.splice(1, 1); // Removes 1 element at index 1
       console.log(arr); // Output: [1, 3]
      

32. What is the difference between map(), filter(), and reduce()?

  • map(): Transforms each element of an array and returns a new array.

      let arr = [1, 2, 3];
      let squared = arr.map((x) => x * x);
      console.log(squared); // Output: [1, 4, 9]
    
  • filter(): Filters elements that satisfy a condition and returns a new array.

      let arr = [1, 2, 3, 4];
      let even = arr.filter((x) => x % 2 === 0);
      console.log(even); // Output: [2, 4]
    
  • reduce(): Reduces an array to a single value by applying a function.

      let arr = [1, 2, 3, 4];
      let sum = arr.reduce((acc, x) => acc + x, 0);
      console.log(sum); // Output: 10
    

33. How do you check if a variable is an array in JavaScript?

Use Array.isArray():

let arr = [1, 2, 3];
console.log(Array.isArray(arr)); // Output: true

let obj = { key: "value" };
console.log(Array.isArray(obj)); // Output: false

34. How do you sort an array of numbers in ascending or descending order?

  • Ascending Order:

      let arr = [3, 1, 4, 2];
      arr.sort((a, b) => a - b);
      console.log(arr); // Output: [1, 2, 3, 4]
    
  • Descending Order:

      arr.sort((a, b) => b - a);
      console.log(arr); // Output: [4, 3, 2, 1]
    

35. What is the difference between forEach() and map()?

  • forEach():

    • Executes a function for each array element.

    • Does not return a new array.

    let arr = [1, 2, 3];
    arr.forEach((x) => console.log(x * 2)); // Output: 2, 4, 6
  • map():

    • Transforms each array element and returns a new array.
    let doubled = arr.map((x) => x * 2);
    console.log(doubled); // Output: [2, 4, 6]

36. How do you flatten a nested array in JavaScript?

Use flat() or recursion:

  1. flat():

     let nested = [1, [2, 3], [4, [5, 6]]];
     let flattened = nested.flat(2); // `2` specifies depth
     console.log(flattened); // Output: [1, 2, 3, 4, 5, 6]
    
  2. Recursion:

     function flatten(arr) {
       return arr.reduce((acc, val) => acc.concat(Array.isArray(val) ? flatten(val) : val), []);
     }
     let nested = [1, [2, 3], [4, [5, 6]]];
     console.log(flatten(nested)); // Output: [1, 2, 3, 4, 5, 6]
    

37. Write a function to remove duplicate values from an array.

Using a Set:

function removeDuplicates(arr) {
  return [...new Set(arr)];
}

let arr = [1, 2, 2, 3, 4, 4];
console.log(removeDuplicates(arr)); // Output: [1, 2, 3, 4]

38. How do you reverse an array in JavaScript?

Use the reverse() method:

let arr = [1, 2, 3, 4];
arr.reverse();
console.log(arr); // Output: [4, 3, 2, 1]

39. Explain the difference between splice() and slice() with examples.

  • splice():

    • Modifies the original array.

    • Adds or removes elements.

    let arr = [1, 2, 3, 4];
    arr.splice(1, 2, "a", "b"); // Remove 2 elements at index 1, add "a" and "b"
    console.log(arr); // Output: [1, "a", "b", 4]
  • slice():

    • Does not modify the original array.

    • Extracts a portion of the array and returns it.

    let arr = [1, 2, 3, 4];
    let sliced = arr.slice(1, 3); // Extract elements from index 1 to 3 (not inclusive)
    console.log(sliced); // Output: [2, 3]
    console.log(arr);    // Output: [1, 2, 3, 4]

40. How can you find the largest or smallest number in an array?

Use Math.max() and Math.min() with the spread operator:

arr = [3, 1, 4, 2];
let largest = Math.max(...arr);
let smallest = Math.min(...arr);

console.log(largest); // Output: 4
console.log(smallest); // Output: 1

5. Strings (10 Questions)

41. How do you check if a string contains a substring in JavaScript?

Use includes():

let str = "Hello, world!";
console.log(str.includes("world")); // Output: true
console.log(str.includes("bye"));   // Output: false

For case-insensitive checks, use toLowerCase():

console.log(str.toLowerCase().includes("hello")); // Output: true

42. What is the difference between charAt() and charCodeAt()?

  • charAt(): Returns the character at a specified index.

      let str = "Hello";
      console.log(str.charAt(1)); // Output: e
    
  • charCodeAt(): Returns the Unicode value of the character at a specified index.

      console.log(str.charCodeAt(1)); // Output: 101
    

43. How do you reverse a string in JavaScript?

You can reverse a string by converting it to an array, reversing it, and joining it back:

function reverseString(str) {
  return str.split("").reverse().join("");
}

console.log(reverseString("Hello")); // Output: olleH

44. Write a function to count the number of vowels in a string.

function countVowels(str) {
  const vowels = "aeiouAEIOU";
  return [...str].filter((char) => vowels.includes(char)).length;
}

console.log(countVowels("Hello, world!")); // Output: 3

45. How do you replace all occurrences of a substring in a string?

Use replaceAll() or a global regular expression:

let str = "Hello world, Hello universe";
let replaced = str.replaceAll("Hello", "Hi");
console.log(replaced); // Output: Hi world, Hi universe

With a regex:

let replacedWithRegex = str.replace(/Hello/g, "Hi");
console.log(replacedWithRegex); // Output: Hi world, Hi universe

46. What is the difference between substr() and substring()?

  • substr(start, length):

    • Extracts a substring starting at start and continuing for length characters.
    let str = "Hello, world!";
    console.log(str.substr(7, 5)); // Output: world
  • substring(start, end):

    • Extracts characters between start and end (not inclusive of end).
    console.log(str.substring(7, 12)); // Output: world

47. How do you split a string into an array of substrings?

Use split():

let str = "apple,banana,orange";
let fruits = str.split(",");
console.log(fruits); // Output: ["apple", "banana", "orange"]

48. Explain template literals and how they are used in JavaScript.

Template literals:

  • Use backticks ` instead of quotes.

  • Allow embedding expressions using ${}.

Example:

let name = "John";
let age = 30;
let message = `Hello, my name is ${name}, and I am ${age} years old.`;
console.log(message); // Output: Hello, my name is John, and I am 30 years old.

49. How do you trim whitespace from the beginning and end of a string?

Use trim():

let str = "   Hello, world!   ";
console.log(str.trim()); // Output: Hello, world!

For trimming only from one side:

  • trimStart() or trimLeft():

      console.log(str.trimStart()); // Output: "Hello, world!   "
    
  • trimEnd() or trimRight():

      console.log(str.trimEnd()); // Output: "   Hello, world!"
    

50. How do you compare two strings in JavaScript?

Use the comparison operators or localeCompare():

let str1 = "apple";
let str2 = "banana";

console.log(str1 === str2); // Output: false
console.log(str1 < str2);   // Output: true

// Using localeCompare
console.log(str1.localeCompare(str2)); // Output: -1 (str1 comes before str2)
console.log(str2.localeCompare(str1)); // Output: 1  (str2 comes after str1)

6. Constructors (5 Questions)

51. What is a constructor function in JavaScript?

  • A constructor function is a function used to create and initialize objects.

  • It acts as a blueprint for creating multiple objects with similar properties or methods.

Example:

function Person(name, age) {
  this.name = name;
  this.age = age;
}

const john = new Person("John", 30);
const jane = new Person("Jane", 25);
console.log(john); // Output: Person { name: "John", age: 30 }
console.log(jane); // Output: Person { name: "Jane", age: 25 }

52. How do you create an object using a constructor function?

To create an object:

  1. Define a constructor function.

  2. Use the new keyword to create an object.

Example:

function Car(make, model) {
  this.make = make;
  this.model = model;
}

const car1 = new Car("Toyota", "Corolla");
const car2 = new Car("Honda", "Civic");
console.log(car1); // Output: Car { make: "Toyota", model: "Corolla" }
console.log(car2); // Output: Car { make: "Honda", model: "Civic" }

53. Explain the concept of new in JavaScript.

The new keyword is used to:

  1. Create a new object.

  2. Set the prototype of the new object to the constructor's prototype.

  3. Bind the this keyword inside the constructor to the new object.

  4. Return the new object.

Example:

function Animal(type) {
  this.type = type;
}

const dog = new Animal("Dog");
console.log(dog.type); // Output: Dog
console.log(dog instanceof Animal); // Output: true

54. What is the difference between class constructors and function constructors?

FeatureFunction ConstructorClass Constructor
SyntaxRegular functionUses the class keyword
Call with newRequiredRequired
Static MethodsNot directly supportedUse static keyword
HoistingHoisted (but not initialized)Not hoisted
InheritancePrototypesextends keyword

Example of Function Constructor:

function Person(name) {
  this.name = name;
}

Person.prototype.greet = function () {
  return `Hello, ${this.name}`;
};

const john = new Person("John");
console.log(john.greet()); // Output: Hello, John

Example of Class Constructor:

class Person {
  constructor(name) {
    this.name = name;
  }

  greet() {
    return `Hello, ${this.name}`;
  }
}

const jane = new Person("Jane");
console.log(jane.greet()); // Output: Hello, Jane

55. How do you extend a class in JavaScript?

Use the extends keyword to inherit properties and methods from another class.

Example:

class Animal {
  constructor(name) {
    this.name = name;
  }

  speak() {
    return `${this.name} makes a sound.`;
  }
}

class Dog extends Animal {
  constructor(name, breed) {
    super(name); // Call the parent class constructor
    this.breed = breed;
  }

  speak() {
    return `${this.name} barks!`;
  }
}

const dog = new Dog("Buddy", "Golden Retriever");
console.log(dog.speak()); // Output: Buddy barks!
console.log(dog instanceof Animal); // Output: true
console.log(dog instanceof Dog);    // Output: true

Here:

  • super calls the constructor of the parent class.

  • Methods in the child class can override parent class methods.


7. Asynchronous JavaScript (10 Questions)

56. What is the difference between synchronous and asynchronous JavaScript?

  • Synchronous JavaScript:

    • Code is executed line by line, blocking the execution of subsequent lines until the current line completes.

    • Example:

        console.log("Start");
        console.log("Middle");
        console.log("End");
        // Output: Start, Middle, End
      
  • Asynchronous JavaScript:

    • Code does not block the execution of subsequent lines.

    • Tasks like I/O operations or timers are executed in the background.

    • Example:

        console.log("Start");
        setTimeout(() => console.log("Middle"), 1000);
        console.log("End");
        // Output: Start, End, Middle
      

57. Explain the concept of callbacks in JavaScript.

A callback is a function passed as an argument to another function, which is executed later.

Example:

function fetchData(callback) {
  setTimeout(() => {
    callback("Data loaded");
  }, 1000);
}

fetchData((message) => {
  console.log(message); // Output: Data loaded
});

58. What are promises, and how are they used in JavaScript?

  • A promise represents a value that may be available now, in the future, or never.

  • Promises have three states: pending, fulfilled, and rejected.

Example:

const fetchData = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve("Data loaded");
  }, 1000);
});

fetchData
  .then((data) => console.log(data)) // Output: Data loaded
  .catch((err) => console.error(err));

59. What is the difference between Promise.all() and Promise.race()?

  • Promise.all():

    • Resolves when all promises are resolved.

    • Rejects if any promise fails.

    const p1 = Promise.resolve(1);
    const p2 = Promise.resolve(2);
    const p3 = Promise.resolve(3);

    Promise.all([p1, p2, p3]).then((results) => console.log(results));
    // Output: [1, 2, 3]
  • Promise.race():

    • Resolves or rejects as soon as one promise resolves or rejects.
    const p1 = new Promise((resolve) => setTimeout(resolve, 100, "One"));
    const p2 = new Promise((resolve) => setTimeout(resolve, 200, "Two"));

    Promise.race([p1, p2]).then((result) => console.log(result));
    // Output: One

60. How do you handle errors in promises?

Use catch() or try...catch with async/await:

// Using catch()
const fetchData = new Promise((resolve, reject) => {
  setTimeout(() => reject("Error occurred"), 1000);
});

fetchData
  .then((data) => console.log(data))
  .catch((err) => console.error(err)); // Output: Error occurred

// Using try...catch with async/await
async function load() {
  try {
    const data = await fetchData;
    console.log(data);
  } catch (err) {
    console.error(err); // Output: Error occurred
  }
}

load();

61. Explain async and await with examples.

  • async: Declares a function that returns a promise.

  • await: Pauses execution of an async function until a promise is resolved or rejected.

Example:

function fetchData() {
  return new Promise((resolve) => {
    setTimeout(() => resolve("Data loaded"), 1000);
  });
}

async function load() {
  console.log("Start");
  const data = await fetchData();
  console.log(data); // Output: Data loaded
  console.log("End");
}

load();
// Output: Start, Data loaded, End

62. What is the purpose of the fetch() API in JavaScript?

The fetch() API is used to make HTTP requests and retrieve data from servers.

Example:

fetch("https://jsonplaceholder.typicode.com/posts/1")
  .then((response) => response.json())
  .then((data) => console.log(data))
  .catch((error) => console.error(error));

63. How does the event loop work in JavaScript?

The event loop is a mechanism that allows JavaScript to handle asynchronous tasks by:

  1. Executing code in the call stack.

  2. Handling async operations using the task queue (macrotasks) and microtask queue.

Example:

console.log("Start");

setTimeout(() => console.log("Timer"), 0); // Macrotask
Promise.resolve().then(() => console.log("Promise")); // Microtask

console.log("End");
// Output: Start, End, Promise, Timer

64. What is a microtask, and how does it differ from a macrotask?

  • Microtasks:

    • Include promises and MutationObserver.

    • Executed before macrotasks.

  • Macrotasks:

    • Include setTimeout, setInterval, and I/O tasks.

Example:

console.log("Start");

setTimeout(() => console.log("Macrotask"), 0); // Macrotask
Promise.resolve().then(() => console.log("Microtask")); // Microtask

console.log("End");
// Output: Start, End, Microtask, Macrotask

65. What are Web Workers in JavaScript?

Web Workers allow JavaScript to run in a separate thread, enabling CPU-intensive tasks without blocking the main thread.

Example:

// worker.js
self.onmessage = function (e) {
  const result = e.data * 2;
  self.postMessage(result);
};

// main.js
const worker = new Worker("worker.js");
worker.postMessage(5);
worker.onmessage = function (e) {
  console.log(e.data); // Output: 10
};

8. Closures (5 Questions)

66. What is a closure in JavaScript?

A closure is a function that "remembers" the variables from its outer scope even after the outer function has finished executing.

Example:

function outer() {
  let count = 0;
  return function inner() {
    count++;
    console.log(count);
  };
}

const increment = outer();
increment(); // Output: 1
increment(); // Output: 2

Here, the inner function forms a closure over the count variable from outer.


67. How do closures help in creating private variables?

Closures allow you to create private variables by encapsulating them within a function, restricting access from outside.

Example:

function Counter() {
  let count = 0; // Private variable
  return {
    increment: function () {
      count++;
      console.log(count);
    },
    decrement: function () {
      count--;
      console.log(count);
    },
  };
}

const counter = Counter();
counter.increment(); // Output: 1
counter.increment(); // Output: 2
counter.decrement(); // Output: 1

// Cannot directly access `count`:
console.log(counter.count); // Output: undefined

68. Write a function that demonstrates the use of closures.

Example: A function to create multiple counters:

function createCounter() {
  let count = 0;
  return function () {
    count++;
    return count;
  };
}

const counter1 = createCounter();
console.log(counter1()); // Output: 1
console.log(counter1()); // Output: 2

const counter2 = createCounter();
console.log(counter2()); // Output: 1 (separate closure)
console.log(counter2()); // Output: 2

69. What are some common use cases of closures in JavaScript?

  1. Data Encapsulation: Protect private variables.

     function BankAccount() {
       let balance = 1000; // Private variable
       return {
         deposit: function (amount) {
           balance += amount;
           console.log(`Balance: ${balance}`);
         },
         withdraw: function (amount) {
           if (amount <= balance) {
             balance -= amount;
             console.log(`Balance: ${balance}`);
           } else {
             console.log("Insufficient funds");
           }
         },
       };
     }
    
     const account = BankAccount();
     account.deposit(500); // Output: Balance: 1500
     account.withdraw(200); // Output: Balance: 1300
    
  2. Event Listeners:

     function attachListener() {
       let counter = 0;
       document.getElementById("btn").addEventListener("click", function () {
         counter++;
         console.log(`Button clicked ${counter} times`);
       });
     }
     attachListener();
    
  3. Function Factories:

     function createMultiplier(factor) {
       return function (value) {
         return value * factor;
       };
     }
    
     const double = createMultiplier(2);
     const triple = createMultiplier(3);
     console.log(double(4)); // Output: 8
     console.log(triple(4)); // Output: 12
    
  4. Memoization:

     function memoize(fn) {
       const cache = {};
       return function (arg) {
         if (cache[arg]) {
           return cache[arg];
         }
         cache[arg] = fn(arg);
         return cache[arg];
       };
     }
    
     const square = memoize((x) => x * x);
     console.log(square(4)); // Output: 16
     console.log(square(4)); // Output: 16 (from cache)
    

70. How do closures impact memory usage in JavaScript?

  • Positive Impact:

    • Closures allow you to maintain state across function calls without polluting the global namespace.
  • Negative Impact:

    • Excessive use of closures can lead to memory leaks, as variables referenced by closures cannot be garbage collected until the closure itself is removed.

    • Example of a potential issue:

        function createLeak() {
          let largeData = new Array(1000).fill("leak");
          return function () {
            console.log(largeData[0]);
          };
        }
      
        const leakyFunction = createLeak();
        // Even though `largeData` is no longer needed, it stays in memory because of the closure.
      
  • Solution:

    • Avoid retaining unnecessary closures.

    • Nullify references when no longer needed:

        let leakyFunction = createLeak();
        leakyFunction = null; // Allows garbage collection
      

9. Object-Oriented Programming (10 Questions)

71. What is object-oriented programming, and how is it implemented in JavaScript?

Object-Oriented Programming (OOP) is a programming paradigm based on the concept of objects that encapsulate data (properties) and behavior (methods).

  • Implementation in JavaScript:

    • Classes: Blueprints for creating objects.

    • Objects: Instances of classes or created via object literals.

    • Key Features: Inheritance, Encapsulation, Polymorphism, and Abstraction.

Example:

class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  greet() {
    console.log(`Hello, my name is ${this.name}.`);
  }
}

const john = new Person("John", 30);
john.greet(); // Output: Hello, my name is John.

72. What is the difference between a class and an object?

ClassObject
Blueprint or template for objectsInstance created from a class
Does not consume memory directlyConsumes memory when instantiated
Defines structure and behaviorContains data and specific state

Example:

class Car {
  constructor(make, model) {
    this.make = make;
    this.model = model;
  }
}

const car1 = new Car("Toyota", "Corolla"); // Object (instance)
console.log(car1); // Output: Car { make: "Toyota", model: "Corolla" }

73. How do you create a class in JavaScript?

Classes are created using the class keyword.

Example:

class Animal {
  constructor(type, sound) {
    this.type = type;
    this.sound = sound;
  }

  makeSound() {
    console.log(`${this.type} says ${this.sound}`);
  }
}

const dog = new Animal("Dog", "Woof");
dog.makeSound(); // Output: Dog says Woof

74. Explain inheritance in JavaScript with an example.

Inheritance allows a class to inherit properties and methods from another class.

Example:

class Animal {
  constructor(name) {
    this.name = name;
  }

  speak() {
    console.log(`${this.name} makes a sound.`);
  }
}

class Dog extends Animal {
  speak() {
    console.log(`${this.name} barks.`);
  }
}

const dog = new Dog("Buddy");
dog.speak(); // Output: Buddy barks.

75. What is the difference between static and instance methods in a class?

Static MethodsInstance Methods
Belong to the class itselfBelong to the instance of the class
Called on the class, not on instancesCalled on instances of the class
Do not access instance-specific dataCan access instance properties

Example:

class MathUtils {
  static add(a, b) {
    return a + b;
  }
}

console.log(MathUtils.add(2, 3)); // Output: 5 (called on the class)

class Person {
  constructor(name) {
    this.name = name;
  }

  greet() {
    console.log(`Hello, ${this.name}`);
  }
}

const person = new Person("Alice");
person.greet(); // Output: Hello, Alice (called on an instance)

76. What is method overriding in JavaScript?

Method overriding allows a subclass to provide a specific implementation of a method defined in the parent class.

Example:

class Animal {
  speak() {
    console.log("Animal makes a sound.");
  }
}

class Dog extends Animal {
  speak() {
    console.log("Dog barks.");
  }
}

const dog = new Dog();
dog.speak(); // Output: Dog barks.

77. How do you implement polymorphism in JavaScript?

Polymorphism allows methods to be used in different ways based on the object that calls them.

Example:

class Shape {
  draw() {
    console.log("Drawing a shape");
  }
}

class Circle extends Shape {
  draw() {
    console.log("Drawing a circle");
  }
}

class Square extends Shape {
  draw() {
    console.log("Drawing a square");
  }
}

const shapes = [new Circle(), new Square(), new Shape()];
shapes.forEach((shape) => shape.draw());
// Output:
// Drawing a circle
// Drawing a square
// Drawing a shape

78. Explain the concept of encapsulation with examples.

Encapsulation restricts access to certain properties or methods, exposing only what is necessary.

Example:

class BankAccount {
  #balance; // Private property

  constructor(initialBalance) {
    this.#balance = initialBalance;
  }

  deposit(amount) {
    this.#balance += amount;
    console.log(`Deposited ${amount}, new balance: ${this.#balance}`);
  }

  withdraw(amount) {
    if (amount > this.#balance) {
      console.log("Insufficient funds");
    } else {
      this.#balance -= amount;
      console.log(`Withdrew ${amount}, remaining balance: ${this.#balance}`);
    }
  }
}

const account = new BankAccount(100);
account.deposit(50); // Output: Deposited 50, new balance: 150
account.withdraw(30); // Output: Withdrew 30, remaining balance: 120
console.log(account.#balance); // Error: Private field '#balance' must be declared in an enclosing class

79. How are abstract classes implemented in JavaScript?

JavaScript does not have built-in abstract classes, but you can simulate them by throwing errors in the base class.

Example:

class Shape {
  constructor() {
    if (this.constructor === Shape) {
      throw new Error("Cannot instantiate an abstract class");
    }
  }

  area() {
    throw new Error("Method 'area()' must be implemented.");
  }
}

class Circle extends Shape {
  constructor(radius) {
    super();
    this.radius = radius;
  }

  area() {
    return Math.PI * this.radius ** 2;
  }
}

const circle = new Circle(5);
console.log(circle.area()); // Output: 78.53981633974483

80. What is the difference between composition and inheritance in JavaScript?

InheritanceComposition
"Is-a" relationship"Has-a" relationship
Subclass inherits from parent classObjects are composed of other objects
Tightly coupledMore flexible and loosely coupled

Example of Inheritance:

class Animal {
  eat() {
    console.log("Animal eats");
  }
}

class Dog extends Animal {
  bark() {
    console.log("Dog barks");
  }
}

const dog = new Dog();
dog.eat(); // Output: Animal eats
dog.bark(); // Output: Dog barks

Example of Composition:

function createDog() {
  return {
    bark: () => console.log("Dog barks"),
    eat: () => console.log("Dog eats"),
  };
}

const dog = createDog();
dog.eat(); // Output: Dog eats
dog.bark(); // Output: Dog barks

10. Functional Programming (10 Questions)

81. What is functional programming, and how does it differ from object-oriented programming?

  • Functional Programming:

    • Focuses on writing pure functions that avoid shared state, mutable data, and side effects.

    • Emphasizes immutability and function composition.

    • Example:

        const double = (x) => x * 2;
        const square = (x) => x * x;
      
        const doubleThenSquare = (x) => square(double(x));
        console.log(doubleThenSquare(3)); // Output: 36
      
  • Object-Oriented Programming (OOP):

    • Organizes code around objects and their properties/methods.

    • Emphasizes encapsulation, inheritance, and polymorphism.

    • Example:

        class Calculator {
          double(x) {
            return x * 2;
          }
      
          square(x) {
            return x * x;
          }
        }
      
        const calc = new Calculator();
        console.log(calc.square(calc.double(3))); // Output: 36
      
FeatureFunctional ProgrammingObject-Oriented Programming
Code OrganizationFunctionsObjects
State ManagementImmutableMutable
Primary FocusWhat to doHow to do
ParadigmDeclarativeImperative

82. What are pure functions, and why are they important?

  • Pure Functions:

    • Always return the same output for the same input.

    • Do not have side effects (e.g., modifying external variables or state).

Example:

// Pure Function
const add = (a, b) => a + b;

// Impure Function
let count = 0;
const increment = () => count++;
  • Importance:

    • Predictable and easier to test.

    • Facilitates debugging and ensures reliable code.


83. Explain immutability in functional programming.

  • Immutability:

    • Data cannot be modified after it is created.

    • Instead of modifying existing data, new copies are created with changes.

Example:

const numbers = [1, 2, 3];

// Immutable operation
const newNumbers = [...numbers, 4];
console.log(numbers); // Output: [1, 2, 3]
console.log(newNumbers); // Output: [1, 2, 3, 4]
  • Benefits:

    • Prevents unexpected side effects.

    • Easier to track state changes.


84. What is the concept of higher-order functions?

A higher-order function:

  1. Takes one or more functions as arguments.

  2. Returns a function as its result.

Example:

const higherOrder = (fn) => (x) => fn(x) * 2;

const square = (x) => x * x;

const doubleSquare = higherOrder(square);
console.log(doubleSquare(3)); // Output: 18
  • Examples in JavaScript: map(), filter(), reduce().

85. What is a side effect in functional programming?

  • Side Effect:

    • Any change in state or behavior outside a function.

    • Examples: Modifying global variables, writing to a file, or logging to the console.

Example of a function with side effects:

let count = 0;

function increment() {
  count++;
  console.log(count); // Side effect
}

increment();
  • Functional programming aims to avoid side effects for predictable and testable code.

86. How is the reduce() method used in functional programming?

  • reduce():

    • Applies a function on each array element to reduce it to a single value.

Example:

const numbers = [1, 2, 3, 4];

const sum = numbers.reduce((acc, curr) => acc + curr, 0);
console.log(sum); // Output: 10

Use cases:

  • Summing an array.

  • Flattening arrays.

  • Counting occurrences.


87. What is the difference between function composition and function currying?

  • Function Composition:

    • Combines multiple functions into one function.
    const double = (x) => x * 2;
    const square = (x) => x * x;

    const compose = (f, g) => (x) => f(g(x));
    const doubleThenSquare = compose(square, double);

    console.log(doubleThenSquare(3)); // Output: 36
  • Function Currying:

    • Transforms a function with multiple arguments into a sequence of functions, each taking a single argument.
    const add = (a) => (b) => a + b;

    const addFive = add(5);
    console.log(addFive(3)); // Output: 8

88. Explain lazy evaluation in JavaScript.

  • Lazy Evaluation:

    • Delays the evaluation of an expression until its value is needed.

    • Often used in generators and iterables.

Example using a generator:

function* lazyRange(start, end) {
  while (start < end) {
    yield start++;
  }
}

const range = lazyRange(1, 5);
console.log(range.next().value); // Output: 1
console.log(range.next().value); // Output: 2

89. How does recursion fit into functional programming?

  • Recursion:

    • A function calls itself to solve smaller instances of a problem.

    • Often used in functional programming as an alternative to loops.

Example:

const factorial = (n) => (n === 0 ? 1 : n * factorial(n - 1));

console.log(factorial(5)); // Output: 120
  • Benefits:

    • Enables declarative solutions for problems like tree traversal and searching.

90. How do you ensure immutability in JavaScript?

  1. Using const:

    • Prevent reassignment.
    const num = 5;
    // num = 6; // Error: Assignment to constant variable.
  1. Spread Operator:

    • Create copies of objects or arrays instead of modifying them.
    const arr = [1, 2, 3];
    const newArr = [...arr, 4];
    console.log(newArr); // Output: [1, 2, 3, 4]
  1. Object.freeze():

    • Prevent modifications to an object.
    const obj = Object.freeze({ a: 1 });
    obj.a = 2; // No effect
    console.log(obj.a); // Output: 1
  1. Libraries:

    • Use libraries like Immutable.js or Immer for managing immutable data structures.

11. Browser and DOM (10 Questions)

91. What is the DOM in JavaScript?

  • The DOM (Document Object Model) is a programming interface for web documents.

  • It represents the structure of a webpage as a tree of objects, allowing JavaScript to interact with and manipulate the document.

Example:

<!DOCTYPE html>
<html>
  <body>
    <h1 id="title">Hello, World!</h1>
  </body>
</html>

The DOM tree for this HTML allows JavaScript to interact with the <h1> element:

const title = document.getElementById("title");
title.textContent = "Hello, DOM!";

92. How do you select an element in the DOM?

  1. By ID:

     const element = document.getElementById("myId");
    
  2. By Class:

     const elements = document.getElementsByClassName("myClass");
    
  3. By Tag:

     const elements = document.getElementsByTagName("div");
    
  4. Using Query Selectors:

     const element = document.querySelector(".myClass"); // Single element
     const elements = document.querySelectorAll(".myClass"); // All matching elements
    

93. What is the difference between innerHTML and textContent?

  • innerHTML:

    • Gets or sets the HTML content of an element, including tags.
    const element = document.getElementById("container");
    element.innerHTML = "<strong>Bold Text</strong>";
  • textContent:

    • Gets or sets only the text content of an element, ignoring tags.
    element.textContent = "<strong>Bold Text</strong>";
    // Output: <strong>Bold Text</strong>
FeatureinnerHTMLtextContent
Includes TagsYesNo
PerformanceSlower due to parsing HTMLFaster
Use CaseInsert/replace HTML structureInsert plain text

94. How do you create, append, and remove elements from the DOM?

  1. Create an Element:

     const newElement = document.createElement("p");
     newElement.textContent = "This is a new paragraph.";
    
  2. Append an Element:

     const container = document.getElementById("container");
     container.appendChild(newElement);
    
  3. Remove an Element:

     container.removeChild(newElement);
    
  4. Alternative Modern Methods:

    • append(): Allows appending text and multiple nodes.

    • remove(): Directly removes an element.

    newElement.remove();

95. What is event delegation in JavaScript?

Event Delegation is a technique where a single event listener is attached to a parent element to handle events on its child elements.

Example:

<ul id="list">
  <li>Item 1</li>
  <li>Item 2</li>
</ul>
const list = document.getElementById("list");

list.addEventListener("click", (event) => {
  if (event.target.tagName === "LI") {
    console.log(event.target.textContent);
  }
});

Here, clicking on any <li> triggers the same listener on the <ul>.


96. How do you prevent the default behavior of an event?

Use the preventDefault() method on the event object.

Example:

<a href="https://example.com" id="link">Click me</a>
const link = document.getElementById("link");
link.addEventListener("click", (event) => {
  event.preventDefault();
  console.log("Default behavior prevented.");
});

97. What is the difference between bubbling and capturing in event propagation?

  • Bubbling:

    • Events propagate from the target element to its ancestors (child โ†’ parent).

    • Default phase for most events.

    element.addEventListener("click", handler);
  • Capturing:

    • Events propagate from ancestors to the target element (parent โ†’ child).

    • Enabled by passing true as the third argument to addEventListener.

    element.addEventListener("click", handler, true);

98. How do you handle asynchronous DOM manipulation?

Asynchronous DOM manipulation can be handled using promises or async/await.

Example:

async function fetchAndAddContent() {
  const response = await fetch("https://jsonplaceholder.typicode.com/posts/1");
  const data = await response.json();

  const container = document.getElementById("container");
  const newElement = document.createElement("p");
  newElement.textContent = data.title;
  container.appendChild(newElement);
}

fetchAndAddContent();

99. What are the different types of events in JavaScript?

  1. Mouse Events:

    • click, dblclick, mouseover, mouseout, mousedown, mouseup, mousemove
  2. Keyboard Events:

    • keydown, keyup, keypress
  3. Form Events:

    • submit, change, focus, blur, input
  4. Window Events:

    • load, resize, scroll, unload
  5. Clipboard Events:

    • copy, cut, paste

Example of a click event:

document.getElementById("button").addEventListener("click", () => {
  console.log("Button clicked!");
});

100. How do you use localStorage and sessionStorage in the browser?

  • localStorage:

    • Stores data with no expiration.

    • Persists across browser sessions.

  • sessionStorage:

    • Stores data for the current session only.

    • Clears when the tab is closed.

Example:

// localStorage
localStorage.setItem("key", "value");
console.log(localStorage.getItem("key")); // Output: value
localStorage.removeItem("key");
localStorage.clear(); // Clears all items

// sessionStorage
sessionStorage.setItem("key", "value");
console.log(sessionStorage.getItem("key")); // Output: value
sessionStorage.removeItem("key");
sessionStorage.clear(); // Clears all items
0
Subscribe to my newsletter

Read articles from Chandan kumar directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Chandan kumar
Chandan kumar

Hello, World! ๐Ÿ‘‹ I'm Chandan Kumar, a passionate and results-driven MEAN stack web developer with a strong background in designing and implementing web applications that deliver exceptional user experiences. I'm dedicated to staying at the forefront of web development trends and technologies to create cutting-edge solutions for my clients. My Expertise: MEAN Stack Development: I specialize in building robust web applications using MongoDB, Express.js, Angular, and Node.js. This full-stack approach allows me to create seamless, end-to-end solutions that meet and exceed client expectations. Front-end Excellence: I have a keen eye for UI/UX design and a deep understanding of front-end technologies such as HTML5, CSS3, and JavaScript. I leverage these skills to craft engaging, responsive, and user-friendly interfaces. Back-end Proficiency: With extensive experience in server-side scripting, API development, and database management, I ensure that the applications I build are not only visually appealing but also highly performant and secure. Problem Solver: I thrive on challenges and enjoy solving complex problems. Whether it's optimizing code for efficiency or troubleshooting issues, I'm committed to finding innovative solutions. My Mission: My mission is to create digital experiences that make a meaningful impact. I'm passionate about collaborating with teams and clients to turn ideas into reality. I believe that technology can empower businesses and individuals alike, and I'm excited to be a part of that journey. Let's Connect: I'm always open to networking and exploring opportunities for collaboration. Whether you're interested in discussing a potential project, sharing insights, or simply connecting with fellow professionals in the tech industry, feel free to reach out. Let's connect and start a conversation! Contact Information: ๐Ÿ“ฉ Email: chandanku845415@gmail.com ๐Ÿ“ฑ LinkedIn: developerchandan ๐ŸŒ Portfolio: developerchandan.github.io โœ๏ธ Medium: developerchandan Thank you for visiting my profile, and I look forward to connecting with you!