J

JavaScript Handbook

Clean • Professional

Intermediate Level JavaScript Interview Questions and Answers

6 minute

Intermediate Level JavaScript Interview Questions and Answers

1. What is the difference between == and ===?

Answer:

  • == performs loose equality with type coercion.
  • === performs strict equality without type coercion.

Example:

console.log(5 == "5");  // true
console.log(5 === "5"); // false

2. What is the ternary operator, and how is it used?

Answer: The ternary operator (?:) is a shorthand for if-else, evaluating a condition and returning one of two values.

Example:

let age = 20;
let status = age >= 18 ? "Adult" : "Minor";
console.log(status); // "Adult"

3. What are string templates (template literals)?

Answer: Template literals, enclosed in backticks (``), allow embedded expressions and multi-line strings.

Example:

let name = "Alice";
console.log(`Hello, ${name}!`); // "Hello, Alice!"

4. What is the BigInt data type?

Answer: BigInt is a primitive type for integers larger than Number.MAX_SAFE_INTEGER (2^53 - 1).

Example:

let big = 123456789012345678901234567890n;
console.log(big + 1n); // 123456789012345678901234567891n

5. How does the sort() method work for arrays?

Answer: Sorts array elements in place. A comparison function can define custom order.

Example:

let arr = [3, 1, 2];
arr.sort((a, b) => a - b); // [1, 2, 3]

6. What are array iteration methods?

Answer: Methods like forEach(), map(), filter(), and reduce() iterate over arrays to process elements.

Example:

let arr = [1, 2, 3];
let doubled = arr.map(x => x * 2); // [2, 4, 6]

7. What is the Date object, and how do you get the current date?

Answer: Represents dates and times. Create a new Date instance to get the current date.

Example:

let now = new Date();
console.log(now); // e.g., 2025-10-18T09:04:00.000Z

8. Difference between for...in and for...of loops

Answer:

  • for...in: Iterates over enumerable properties of an object.
  • for...of: Iterates over iterable values like arrays or strings.

Example:

let arr = [1, 2, 3];
for (let i in arr) console.log(i); // "0", "1", "2"
for (let v of arr) console.log(v); // 1, 2, 3

9. What are arrow functions, and how do they differ from regular functions?

Answer: Arrow functions (=>) have concise syntax and lexical this binding.

Example:

const add = (a, b) => a + b;
console.log(add(2, 3)); // 5

10. What is the this keyword in JavaScript?

Answer: Refers to the context in which a function is called. It varies based on invocation (object, global, or undefined in strict mode).

Example:

const obj = {
  name: "John",
  greet() { console.log(this.name); }
};
obj.greet(); // "John"

11. What are closures in JavaScript?

Answer: A closure is a function that retains access to its outer scope’s variables even after the outer function has finished executing.

Example:

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

12. What is object destructuring?

Answer: Extracts properties from objects into variables.

Example:

let person = { name: "Alice", age: 25 };
let { name, age } = person;
console.log(name, age); // "Alice", 25

13. What is the purpose of Object.freeze()?

Answer: Prevents modifications to an object, making it immutable.

Example:

let obj = Object.freeze({ name: "John" });
obj.name = "Jane"; // Ignored
console.log(obj.name); // "John"

14. What are JavaScript classes, and how do they work?

Answer: Classes are blueprints for creating objects with shared properties and methods, supporting inheritance via extends.

Example:

class Person {
  constructor(name) { this.name = name; }
  greet() { return `Hello, ${this.name}`; }
}
let p = new Person("Alice");
console.log(p.greet()); // "Hello, Alice"

15. What is a Set in JavaScript?

Answer: A Set is a collection of unique values with methods like add(), has(), and delete().

Example:

let set = new Set([1, 2, 2, 3]);
console.log(set); // Set {1, 2, 3}

16. What is a Map in JavaScript?

Answer: A Map is a key-value collection where keys can be any type.

Example:

let map = new Map();
map.set("key", "value");
console.log(map.get("key")); // "value"

17. What are iterators in JavaScript?

Answer: Iterators are objects with a next() method returning { value, done } for custom iteration.

Example:

let arr = [1, 2];
let it = arr[Symbol.iterator]();
console.log(it.next()); // { value: 1, done: false }

18. What are regular expressions (RegExp) in JavaScript?

Answer: Patterns used for matching, searching, or replacing strings.

Example:

let str = "Hello123";
console.log(/\\d+/.test(str)); // true

19. What are callbacks in JavaScript?

Answer: Functions passed as arguments to execute after an operation completes.

Example:

setTimeout(() => console.log("Delayed"), 1000);

20. What is event handling in JavaScript?

Answer: Responding to user actions using event listeners like addEventListener.

Example:

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

21. What is event propagation?

Answer: Events travel through the DOM via bubbling (child → parent) or capturing (parent → child).

Example:

document.getElementById("child").addEventListener("click", () => {
  console.log("Child clicked");
}, true); // Capture phase

22. What is try...catch used for?

Answer: Handles errors gracefully by catching exceptions.

Example:

try {
  throw new Error("Something went wrong");
} catch (e) {
  console.log(e.message); // "Something went wrong"
}

23. What is strict mode in JavaScript?

Answer: "use strict" enforces stricter parsing and prevents unsafe actions like undeclared variables.

Example:

"use strict";
x = 10; // ReferenceError

24. What is the DOM, and how do you access elements?

Answer: The Document Object Model represents HTML as a tree of objects. Access elements via getElementById, querySelector, etc.

Example:

let elem = document.querySelector(".myClass");
elem.textContent = "Updated";

25. What is the Window object in the Browser Object Model (BOM)?

Answer: Represents the browser window, providing methods like alert() and setTimeout().

Example:

window.alert("Hello!");

26. What is localStorage in JavaScript?

Answer: Web API for storing persistent key-value pairs in the browser.

Example:

localStorage.setItem("name", "John");
console.log(localStorage.getItem("name")); // "John"

27. What is AJAX, and how does it work?

Answer: AJAX allows asynchronous data fetching without reloading the page. Can use XMLHttpRequest or fetch().

Example:

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

28. What is JSON, and how do you parse it?

Answer: JSON is a lightweight data format. Use JSON.parse() to convert JSON strings to objects, JSON.stringify() to convert objects to strings.

Example:

let json = '{"name": "John"}';
let obj = JSON.parse(json);
console.log(obj.name); // "John"

29. Difference between call() and apply()

Answer: Both set this context.

  • call(): Arguments individually
  • apply(): Arguments as array

Example:

function greet(greeting) {
  console.log(`${greeting}, ${this.name}`);
}
let obj = { name: "Alice" };
greet.call(obj, "Hello");   // "Hello, Alice"
greet.apply(obj, ["Hi"]);   // "Hi, Alice"

30. What are higher-order functions?

Answer: Functions that take other functions as arguments or return functions.

Example:

function higher(func) {
  return func();
}
higher(() => "Hello!"); // "Hello!"

 

Article 0 of 0