J

JavaScript Handbook

Clean • Professional

Advanced Level JavaScript Interview Questions and Answers

6 minute

Advanced Level JavaScript Interview Questions and Answers

1. Difference between shallow and deep copying in JavaScript

Answer:

  • Shallow copy: Copies top-level properties; nested objects remain references.
  • Deep copy: Copies all levels, creating independent objects.

Example:

let obj = { a: 1, b: { c: 2 } };
let shallow = { ...obj };
let deep = JSON.parse(JSON.stringify(obj));

shallow.b.c = 3;
console.log(obj.b.c); // 3 (shallow affects original)
console.log(deep.b.c); // 2 (deep is independent)

2. What is the prototype chain?

Answer: The prototype chain is a mechanism for property lookup where an object inherits properties from its prototype, recursively up to null.

Example:

let animal = { eats: true };
let dog = Object.create(animal);
console.log(dog.eats); // true (inherited via prototype)

3. What are generators, and how do they work?

Answer: Generators (using function*) can pause and resume execution, yielding values one at a time.

Example:

function* generator() {
  yield 1;
  yield 2;
}
let gen = generator();
console.log(gen.next().value); // 1
console.log(gen.next().value); // 2

4. Difference between Promise.all(), Promise.race(), and Promise.any()

Answer:

  • Promise.all(): Resolves when all promises resolve; rejects on first failure.
  • Promise.race(): Resolves/rejects as soon as one promise settles.
  • Promise.any(): Resolves when any promise resolves; rejects if all fail.

Example:

let p1 = Promise.resolve("One");
let p2 = Promise.reject("Error");

Promise.all([p1, p2]).catch(err => console.log(err)); // "Error"

5. What are WeakSet and WeakMap?

Answer:

  • WeakSet: Stores weakly held objects; allows garbage collection.
  • WeakMap: Key-value pairs with object keys held weakly.

Example:

let weakMap = new WeakMap();
let key = {};
weakMap.set(key, "value");
console.log(weakMap.get(key)); // "value"

6. What is async/await, and how are errors handled?

Answer: Simplifies asynchronous code; errors handled using try...catch.

Example:

async function fetchData() {
  try {
    let response = await fetch("<https://api.example.com/data>");
    return await response.json();
  } catch (error) {
    console.error("Error:", error);
  }
}

7. What is event delegation, and why is it useful?

Answer: Attaches a single listener to a parent to handle child events, improving performance and handling dynamic elements.

Example:

document.getElementById("parent").addEventListener("click", (e) => {
  if (e.target.tagName === "BUTTON") console.log("Button clicked");
});

8. What is the bind() method?

Answer: Creates a new function with a fixed this context and optional arguments.

Example:

let obj = { name: "Alice" };
function greet() { console.log(this.name); }
let boundGreet = greet.bind(obj);
boundGreet(); // "Alice"

9. What are JavaScript modules, and how do you use them?

Answer: Modules organize code using import and export for reusability and encapsulation.

Example:

// math.js
export function add(a, b) { return a + b; }

// main.js
import { add } from './math.js';
console.log(add(2, 3)); // 5

10. What is the debugger statement?

Answer: Pauses execution in a debugging tool to inspect variables and call stack.

Example:

function test() {
  let x = 10;
  debugger; // Pauses here
  console.log(x);
}

11. Difference between Object.seal() and Object.preventExtensions()

Answer:

  • Object.seal(): Cannot add/remove properties but can modify existing.
  • Object.preventExtensions(): Cannot add new properties; existing can be modified/deleted.

Example:

let obj = { a: 1 };
Object.seal(obj);
obj.b = 2; // Ignored
obj.a = 3; // Allowed

12. What is a pure function?

Answer: Always returns same output for same input; has no side effects.

Example:

function add(a, b) { return a + b; } // Pure

13. What is the Fetch API, and how does it differ from XMLHttpRequest?

Answer: Promise-based modern HTTP requests, simpler and more flexible than XMLHttpRequest.

Example:

fetch("<https://api.example.com/data>")
  .then(res => res.json())
  .then(data => console.log(data));

14. What is the Canvas API?

Answer: Renders 2D graphics dynamically inside a <canvas> element.

Example:

let canvas = document.getElementById("myCanvas");
let ctx = canvas.getContext("2d");
ctx.fillRect(10, 10, 50, 50);

15. What is the Clipboard API?

Answer: Reads/writes to the system clipboard (copy-paste functionality).

Example:

navigator.clipboard.writeText("Copied!").then(() => console.log("Text copied"));

16. What are JavaScript typed arrays?

Answer: Array-like objects for handling binary data with fixed-size elements (e.g., Int32Array, Float64Array).

Example:

let arr = new Int32Array([1, 2, 3]);
console.log(arr[0]); // 1

17. What is the Worker API and Web Workers?

Answer: Run scripts in background threads, enabling parallel execution without blocking the main thread.

Example:

// worker.js
self.onmessage = () => self.postMessage("Done");

// main.js
let worker = new Worker("worker.js");
worker.onmessage = (e) => console.log(e.data); // "Done"

18. What is the Geolocation API?

Answer: Retrieves the user’s location (with permission) as latitude/longitude.

Example:

navigator.geolocation.getCurrentPosition(pos => {
  console.log(pos.coords.latitude, pos.coords.longitude);
});

19. What is function currying?

Answer: Transforms a multi-argument function into a sequence of single-argument functions.

Example:

function curryAdd(a) { return b => a + b; }
console.log(curryAdd(2)(3)); // 5

20. What is memoization?

Answer: Caches function results to avoid redundant computations.

Example:

function memoize(fn) {
  let cache = {};
  return function(...args) {
    let key = JSON.stringify(args);
    if (cache[key]) return cache[key];
    return (cache[key] = fn(...args));
  };
}

21. Difference between bubbling and capturing in event propagation

Answer:

  • Bubbling: Events propagate from the target element up to ancestors.
  • Capturing: Events propagate from ancestors down to the target.

Example:

document.getElementById("parent").addEventListener("click", () => {
  console.log("Parent captured");
}, true); // Capturing phase

22. What are Symbols and why are they used?

Answer: Unique, immutable primitives used as object keys to avoid naming collisions.

Example:

let sym = Symbol("id");
let obj = { [sym]: 123 };
console.log(obj[sym]); // 123

23. What is structuredClone()?

Answer: Creates a deep copy of objects, preserving nested structures.

Example:

let obj = { a: { b: 1 } };
let copy = structuredClone(obj);
copy.a.b = 2;
console.log(obj.a.b); // 1

24. Purpose of Object.create()

Answer: Creates a new object with a specified prototype for inheritance without constructors.

Example:

let proto = { greet: () => "Hello" };
let obj = Object.create(proto);
console.log(obj.greet()); // "Hello"

25. What are Immediately Invoked Function Expressions (IIFE)?

Answer: Functions executed immediately to create private scopes and avoid polluting the global namespace.

Example:

(function() {
  let x = 10;
  console.log(x); // 10
})();

26. Async function’s implicit promise behavior

Answer: Always returns a Promise, resolving to the return value or rejecting on error.

Example:

async function test() { return "Success"; }
test().then(val => console.log(val)); // "Success"

27. What is the Proxy object?

Answer: Wraps an object to intercept/customize operations like property access or assignment.

Example:

let target = { name: "John" };
let proxy = new Proxy(target, {
  get: (obj, prop) => obj[prop] || "Not found"
});
console.log(proxy.age); // "Not found"

28. What are private fields in classes?

Answer: Prefixed with #, restricting access within the class, enhancing encapsulation.

Example:

class Person {
  #name = "John";
  getName() { return this.#name; }
}
let p = new Person();
console.log(p.getName()); // "John"

29. Role of the Reflect API

Answer: Provides methods for interceptable operations, often used with Proxy.

Example:

let obj = { a: 1 };
console.log(Reflect.get(obj, "a")); // 1

30. What are JavaScript decorators?

Answer: Experimental syntax for annotating/modifying classes or methods, used for metaprogramming.

Example (TypeScript):

function log(target, key) { console.log(`${key} was called`); }
class MyClass {
  @log
  myMethod() {}
}

 

Article 0 of 0