Skip to main content

Command Palette

Search for a command to run...

Top 50+ Essential JavaScript Interview Questions You Need to Know

Top JavaScript Interview Questions for Those with 2+ Years Experience

Updated
10 min read
Top 50+ Essential JavaScript Interview Questions You Need to Know
I

Hello there! My name is Indrajeet, and I am a skilled web developer passionate about creating innovative, user-friendly, and dynamic web applications. 📌My Expertise advanced proficiency in angular front-End Development. Back-End Development Leveraging the power of .NET, I build secure, robust, and scalable server-side architectures.

Introduction:

Dive into this curated set of 50 JavaScript questions and answers, complete with code snippets, to strengthen your understanding of core concepts and practical implementations. Whether you're a beginner building a solid foundation or an intermediate learner looking to polish your skills, these questions will help you grasp key JavaScript principles effectively.

If you find these 50 questions helpful and are eager to explore even more, don’t miss the extended collection of 100 additional JavaScript questions and answers with detailed explanations and code snippets! Click here to continue your learning journey!

50 JavaScript questions and answers

  1. What is JavaScript?

JavaScript is a lightweight, interpreted programming language used to create dynamic web content.


2. What are JavaScript data types?

  • Primitive: String, Number, Boolean, Undefined, Null, Symbol, BigInt

  • Non-Primitive: Object, Array, Function

let str = "Hello"; // String
let num = 42;      // Number
let bool = true;   // Boolean

3. Explain var, let, and const

  • var: Function-scoped, can be re-declared.

  • let: Block-scoped, cannot be re-declared.

  • const: Block-scoped, must be initialized and cannot be reassigned.

var a = 10;
let b = 20;
const c = 30;

4. What is hoisting?

Hoisting allows function and variable declarations to be moved to the top of their scope during compile time.

console.log(x); // undefined
var x = 10;

5. Difference between == and ===

  • ==: Abstract equality, checks value.

  • ===: Strict equality, checks value and type.

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

6. What are closures in JavaScript?

Closures allow a function to access variables from its outer scope.

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

7. What is the DOM?

The DOM (Document Object Model) is an API that represents HTML as a tree structure.


8. Explain event delegation.

Event delegation uses a parent to handle events for its child elements, read this blog post for more reference.

document.getElementById('parent').addEventListener('click', (e) => {
  console.log('Clicked on', e.target);
});

9. What are promises?

Promises handle asynchronous operations and can be in states: pending, fulfilled, or rejected.

const promise = new Promise((resolve, reject) => {
  resolve("Success");
});
promise.then((res) => console.log(res));

10. Explain async/await.

async/await is a cleaner way to handle promises.

async function fetchData() {
  let data = await fetch('https://api.example.com');
  console.log(data);
}
fetchData();

11. What are arrow functions?

Arrow functions are a shorter syntax for functions.

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

12. What is the spread operator?

The spread operator (...) expands an array or object.

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

13. Difference between undefined and null

  • undefined: Variable declared but not initialized.

  • null: Explicitly set to no value.


14. What is this in JavaScript?

this refers to the context in which the function is executed.


15. Explain call, apply, and bind.

  • call: Invokes a function with arguments as a list.

  • apply: Invokes a function with arguments as an array.

  • bind: Returns a new function bound to a context.

function greet(greeting) {
  console.log(`${greeting}, ${this.name}`);
}
const user = { name: "John" };
greet.call(user, "Hello");

16. Explain prototypes in JavaScript.

Prototypes are the mechanism by which objects inherit features.

function Person(name) {
  this.name = name;
}
Person.prototype.greet = function () {
  return `Hello, ${this.name}`;
};
const john = new Person('John');
console.log(john.greet());

17. What are IIFEs?

Immediately Invoked Function Expressions execute immediately after definition.

(function () {
  console.log("IIFE called");
})();

18. Difference between map, filter, and reduce

  • map: Transforms elements.

  • filter: Filters elements.

  • reduce: Reduces to a single value.

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

19. What is the event loop?

The event loop manages the execution of asynchronous code in JavaScript.


20. What are modules in JavaScript?

Modules allow code reuse using export and import.

// module.js
export const greet = () => console.log("Hello");

// main.js
import { greet } from './module.js';
greet();

21. What is strict mode in JavaScript?

strict mode is a feature that enforces stricter parsing and error handling.

'use strict';
x = 10; // Error: x is not defined

22. What are higher-order functions?

Higher-order functions are functions that take other functions as arguments or return functions.

function higherOrder(fn) {
  return fn(5);
}
function addTwo(num) {
  return num + 2;
}
console.log(higherOrder(addTwo)); // 7

23. Explain debouncing and throttling.

  • Debouncing: Ensures a function runs after a delay, resetting if called again.

  • Throttling: Ensures a function runs at fixed intervals.

// Debouncing
function debounce(func, delay) {
  let timer;
  return function (...args) {
    clearTimeout(timer);
    timer = setTimeout(() => func.apply(this, args), delay);
  };
}

24. What is the difference between deep copy and shallow copy?

  • Shallow Copy: Copies only the first level.

  • Deep Copy: Recursively copies all levels.

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

25. Explain setTimeout and setInterval.

  • setTimeout: Runs code after a specified time.

  • setInterval: Repeats code execution at intervals.

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

26. What is the difference between Object.freeze and Object.seal?

  • Object.freeze: Makes an object immutable.

  • Object.seal: Allows modifying properties but prevents adding or removing them.

let obj = { a: 1 };
Object.freeze(obj);
obj.a = 2; // Error

27. What are getters and setters in JavaScript?

Getters and setters allow controlled access to object properties.

let obj = {
  _name: "John",
  get name() {
    return this._name;
  },
  set name(value) {
    this._name = value;
  },
};
obj.name = "Doe";
console.log(obj.name); // "Doe"

28. What are JavaScript generators?

Generators are functions that can pause and resume execution using yield.

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

29. What is the difference between synchronous and asynchronous code?

  • Synchronous: Code executes sequentially.

  • Asynchronous: Code execution is non-blocking.


30. What is the Fetch API?

The Fetch API allows making HTTP requests.

fetch('https://api.example.com')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error));

31. Explain localStorage and sessionStorage.

  • localStorage: Stores data with no expiration.

  • sessionStorage: Stores data for the session.

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

32. What are JavaScript classes?

Classes are syntactic sugar over prototypes for creating objects.

class Person {
  constructor(name) {
    this.name = name;
  }
  greet() {
    return `Hello, ${this.name}`;
  }
}
const john = new Person("John");
console.log(john.greet());

33. What are the differences between forEach and map?

  • forEach: Iterates over elements without returning a new array.

  • map: Iterates over elements and returns a new array.

let arr = [1, 2, 3];
arr.forEach(num => console.log(num)); // No new array
let doubled = arr.map(num => num * 2); // [2, 4, 6]

34. Explain try...catch in JavaScript.

try...catch handles exceptions.

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

35. What is the EventEmitter in JavaScript?

EventEmitter allows emitting and listening for custom events (Node.js).

const EventEmitter = require('events');
const emitter = new EventEmitter();
emitter.on('event', () => console.log('Event triggered'));
emitter.emit('event');

36. What are WeakMap and WeakSet?

  • WeakMap: Holds weakly referenced key-value pairs.

  • WeakSet: Holds weakly referenced objects.

let obj = {};
let weakMap = new WeakMap();
weakMap.set(obj, "value");

37. What is memoization?

Memoization optimizes function calls by caching results.

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

38. What is the difference between apply, call, and bind?

  • apply: Invokes with an array of arguments.

  • call: Invokes with arguments as a list.

  • bind: Returns a new function bound to a context.

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

39. Explain polyfills in JavaScript.

Polyfills are code snippets that add modern features to older environments.


40. What is a service worker?

A service worker is a script that runs in the background and helps enable features like offline caching.

navigator.serviceWorker.register('/sw.js').then(() => {
  console.log('Service Worker Registered');
});

41. What is the Event Loop in JavaScript?

The Event Loop is a mechanism that handles the execution of asynchronous code. It checks the call stack and the task queue to decide what code to execute next.

Code Example:

console.log('Start'); 

setTimeout(() => console.log('Timeout'), 0);

Promise.resolve().then(() => console.log('Promise'));

console.log('End');

Output:

Start
End
Promise
Timeout

Explanation:

  • The call stack executes Start and End.

  • The promise is a microtask, so it runs before the timeout (a macrotask).


42. What is the difference between setImmediate and process.nextTick in Node.js?

  • process.nextTick: Executes the callback immediately after the current operation, before any I/O events.

  • setImmediate: Executes the callback on the next iteration of the event loop.

Code Example:

console.log('Start');

process.nextTick(() => console.log('Next Tick'));
setImmediate(() => console.log('Immediate'));

console.log('End');

Output:

Start
End
Next Tick
Immediate

43. What is Prototypal Inheritance in JavaScript?

Prototypal inheritance allows objects to inherit properties and methods from another object using the prototype chain.

Code Example:

const parent = {
  greet: function() {
    console.log(`Hello, ${this.name}`);
  }
};

const child = Object.create(parent);
child.name = 'John';
child.greet(); // Hello, John

44. What is the difference between __proto__ and prototype?

  • __proto__: Refers to the prototype of an object instance.

  • prototype: Refers to the prototype of a function (used when creating objects via constructors).

Code Example:

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

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

const john = new Person('John');
console.log(john.__proto__ === Person.prototype); // true

45. How do you use closures to implement private variables?

Closures can create private variables by encapsulating data within a function scope.

Code Example:

function Counter() {
  let count = 0; // Private variable

  return {
    increment: function() {
      count++;
      return count;
    },
    decrement: function() {
      count--;
      return count;
    }
  };
}

const counter = Counter();
console.log(counter.increment()); // 1
console.log(counter.decrement()); // 0
console.log(counter.count); // undefined (private)

46. What is the difference between shallow copy and deep copy in JavaScript?

  • Shallow Copy: Copies the first level of properties; nested objects are referenced.

  • Deep Copy: Recursively copies all levels of properties.

Code Example:

const obj = { a: 1, b: { c: 2 } };

// Shallow Copy
const shallowCopy = { ...obj };
shallowCopy.b.c = 42;
console.log(obj.b.c); // 42

// Deep Copy
const deepCopy = JSON.parse(JSON.stringify(obj));
deepCopy.b.c = 99;
console.log(obj.b.c); // 42

47. How would you implement a debounce function in JavaScript?

A debounce function ensures that a function is executed only after a specified delay, even if it is called repeatedly.

Code Example:

function debounce(func, delay) {
  let timeout;
  return function (...args) {
    clearTimeout(timeout);
    timeout = setTimeout(() => func.apply(this, args), delay);
  };
}

const log = debounce((msg) => console.log(msg), 500);
log('Hello'); // Executes after 500ms if not called again

48. How would you implement a throttle function in JavaScript?

A throttle function ensures that a function is executed at most once in a specified interval, even if called repeatedly.

Code Example:

function throttle(func, interval) {
  let lastCall = 0;
  return function (...args) {
    const now = Date.now();
    if (now - lastCall >= interval) {
      lastCall = now;
      func.apply(this, args);
    }
  };
}

const log = throttle((msg) => console.log(msg), 1000);
log('Hello'); // Executes immediately
log('Hello again'); // Ignored if within 1 second

49. How do you implement memoization in JavaScript?

Memoization is a caching technique to store the results of expensive function calls.

Code Example:

function memoize(fn) {
  const cache = {};
  return function (n) {
    if (cache[n]) {
      return cache[n];
    }
    cache[n] = fn(n);
    return cache[n];
  };
}

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

console.log(factorial(5)); // 120
console.log(factorial(5)); // Retrieved from cache: 120

50. What are WeakMap and WeakSet?

  • WeakMap: Holds key-value pairs where keys are weakly referenced.

  • WeakSet: Stores objects weakly, preventing memory leaks.

Code Example:

const weakMap = new WeakMap();
const obj = {};
weakMap.set(obj, 'value');
console.log(weakMap.get(obj)); // value

const weakSet = new WeakSet();
weakSet.add(obj);
console.log(weakSet.has(obj)); // true

Moving forward:

If you find these 50 questions helpful and are eager to explore even more, don’t miss the extended collection of 100 additional JavaScript questions and answers with detailed explanations and code snippets! Click here to continue your learning journey!

Interviews kit

Part 7 of 9

A series of practical interview questions with clear answers and code snippets to master key programming concepts.

Up next

Git Made Easy: 100 Questions with Solutions

Discover 100 Fundamental Git Questions and Their Solutions

More from this blog

C

CodeWords

35 posts

Codewords is a comprehensive coding blog offering in-depth tutorials, practical tips, expert insights, and career guidance. Join us and start coding like a pro today!