avatarKomeil Mehranfar

Summarize

Part 3–100 Advanced JavaScript Interview Questions with Answers and Code Examples

Part 3–100 Advanced JavaScript Interview Questions with Answers and Code Examples

Introduction:

Elevate your JavaScript expertise with a collection of 10 additional advanced interview questions. Explore intricate concepts such as lexical scoping, design patterns, asynchronous programming, and more. Gain valuable insights and master these topics with detailed answers and practical code examples. Prepare to excel in your JavaScript interviews and showcase your proficiency in this dynamic language. (Part 3 of the series)

Check out 100 Advanced JavaScript Interview Questions with Answers and Code Examples (Part 2) if you didn’t read that article!

  • What is the difference between shallow copy and deep copy in JavaScript? Provide examples for each.
  • Explain the concept of immutability in JavaScript and why it is important. Provide an example.
  • What is a generator function in JavaScript? Provide an example of its usage.
  • Explain the concept of event bubbling in JavaScript and how to stop it. Provide an example.
  • What are the differences between function declarations and function expressions in JavaScript? Provide examples for each.
  • Explain the concept of the “rest” parameter in JavaScript functions and provide an example of its usage.
  • What is the purpose of the Object.setPrototypeOf() method in JavaScript? Provide an example.
  • Explain the concept of the event-driven programming paradigm in JavaScript and provide an example.
  • What are JavaScript Promises, and how do they work? Provide an example.
  • Explain the concept of the module pattern in JavaScript and provide an example.

21- What is the difference between shallow copy and deep copy in JavaScript? Provide examples for each.

Answer:

1- Shallow copy: A shallow copy creates a new object that references the original object's properties. Modifying the properties of the new object may affect the original object.

const originalObj = { name: 'John', age: 30 };
const shallowCopy = Object.assign({}, originalObj);

shallowCopy.name = 'Jane';
console.log(originalObj.name); // Output: 'John'

2- Deep copy: A deep copy creates a new object with its own unique set of properties, recursively copying all nested objects and arrays.

const originalObj = { name: 'John', age: 30 };
const deepCopy = JSON.parse(JSON.stringify(originalObj));

deepCopy.name = 'Jane';
console.log(originalObj.name); // Output: 'John'

22- Explain the concept of immutability in JavaScript and why it is important. Provide an example.

Answer:

Immutability refers to the inability of an object (or its state) to be modified after it is created. In JavaScript, primitive values (e.g., strings, numbers) are immutable, while objects and arrays are mutable. Immutability is important because it helps avoid unintended side effects, enables simpler state management, and improves performance.

const originalObj = { name: 'John' };
const newObj = { ...originalObj, age: 30 };

console.log(originalObj); // Output: { name: 'John' }
console.log(newObj); // Output: { name: 'John', age: 30 }

In the example, instead of modifying the original object, a new object is created with the desired changes. This ensures the immutability of the original object.

23- What is a generator function in JavaScript? Provide an example of its usage.

Answer:

A generator function is a special type of function that can be paused and resumed during its execution. It is defined using the function* syntax and uses the yield keyword to yield a sequence of values.

function* countUpTo(max) {
  for (let i = 1; i <= max; i++) {
    yield i;
  }
}

const generator = countUpTo(5);

console.log(generator.next().value); // Output: 1
console.log(generator.next().value); // Output: 2
console.log(generator.next().value); // Output: 3

In the example, the countUpTo generator function yields a sequence of numbers up to a given maximum value. Each call to generator.next() returns an object with the value property containing the next yielded value.

24- Explain the concept of event bubbling in JavaScript and how to stop it. Provide an example.

Answer:

Event bubbling is a phenomenon where an event triggered on a nested element is also triggered on its parent elements in the DOM hierarchy. It follows the order from the innermost element to the outermost element. To stop event bubbling, the event.stopPropagation() method can be used.

document.getElementById('inner').addEventListener('click', event => {
  console.log('Inner element clicked');
  event.stopPropagation();
});

document.getElementById('outer').addEventListener('click', event => {
  console.log('Outer element clicked');
});

In the example, clicking the inner element will only log "Inner element clicked" and prevent the event from bubbling up to the outer element.

25- What are the differences between function declarations and function expressions in JavaScript? Provide examples for each.

Answer:

1- Function declaration:

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

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

2- Function expression:

const sum = function(a, b) {
  return a + b;
};

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

The main difference is that function declarations are hoisted and can be called before they are defined, whereas function expressions are not hoisted and must be defined before they are called.

26- Explain the concept of the "rest" parameter in JavaScript functions and provide an example of its usage.

Answer:

The "rest" parameter allows a function to accept an indefinite number of arguments as an array. It is denoted by three dots (...) followed by the parameter name. The rest parameter collects the remaining arguments passed to the function.

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

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

In the example, the sum function can accept any number of arguments, and the numbers parameter will be an array containing all the arguments passed.

27- What is the purpose of the Object.setPrototypeOf() method in JavaScript? Provide an example.

Answer:

The Object.setPrototypeOf() method is used to set the prototype (i.e., the internal [[Prototype]] property) of an object.

const parent = { name: 'John' };
const child = { age: 30 };

Object.setPrototypeOf(child, parent);

console.log(child.name); // Output: 'John'

In the example, the "child" object's prototype is set to the parent object, allowing the "child" object to inherit the "name" property from its prototype.

28- Explain the concept of the event-driven programming paradigm in JavaScript and provide an example.

Answer:

Event-driven programming is a programming paradigm where the flow of the program is determined by events that occur, such as user actions or system events. The program responds to these events by executing corresponding event handlers or callbacks.

document.getElementById('btn').addEventListener('click', () => {
  console.log('Button clicked');
});

In the example, the program waits for the "click" event to occur on the button element with the id "btn". Once the event is triggered (e.g., when the button is clicked), the specified callback function is executed.

29- What are JavaScript Promises, and how do they work? Provide an example.

Answer:

Promises are a built-in feature in JavaScript used for handling asynchronous operations. They represent the eventual completion (or failure) of an asynchronous task and allow chaining of multiple asynchronous operations.

function fetchData() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const data = 'Sample data';
      resolve(data);
    }, 2000);
  });
}

fetchData()
  .then(data => {
    console.log(data);
  })
  .catch(error => {
    console.error(error);
  });

In the example, the fetchData function returns a Promise that resolves with the data after a simulated asynchronous delay of 2 seconds. The .then() method is used to handle the resolved value, and the .catch() method is used to handle any errors that occur.

30- Explain the concept of the module pattern in JavaScript and provide an example.

Answer:

The module pattern is a design pattern used to encapsulate and organize code by creating self-contained modules with private and public members. It helps in achieving modularity, encapsulation, and separation of concerns.

const counterModule = (function() {
  let count = 0;

  function increment() {
    count++;
  }

  function decrement() {
    count--;
  }

  function getCount() {
    return count;
  }

  return {
    increment,
    decrement,
    getCount
  };
})();

console.log(counterModule.getCount()); // Output: 0
counterModule.increment();
counterModule.increment();
console.log(counterModule.getCount()); // Output: 2

In the example, the module pattern creates a counter module with private count variable and public methods increment, decrement, and getCount. The private variable is accessible only within the module, and the public methods provide controlled access to the private state.

These ten supplementary JavaScript interview questions delve into advanced concepts and problem-solving abilities, providing a comprehensive evaluation of a candidate's proficiency. Each question is accompanied by insightful code examples, enabling a deeper understanding of complex topics. With these thought-provoking questions, assess candidates' expertise in advanced JavaScript and their ability to apply it effectively.

Further Reading: Part 4

Previous Articles:

Part 1–100 Advanced JavaScript Interview Questions with Answers and Code Examples

Part 2–100 Advanced JavaScript Interview Questions with Answers and Code Examples

Follow me on Medium if you liked the Article.

Js
JavaScript
Js Interview Questions
Javascript Interview
Recommended from ReadMedium