Posted in

Top 30 JavaScript Interview Questions and Answers for All Levels

Basic JavaScript Interview Questions (Freshers)

Question 1: What is the difference between == and === in JavaScript?

The == operator performs type coercion before comparison, while === compares both value and type without coercion. For example, 5 == '5' returns true, but 5 === '5' returns false.

Question 2: What are the different data types in JavaScript?

JavaScript has primitive data types: undefined, null, boolean, number, bigint, string, and symbol. It also has reference types like object (including arrays and functions).

Question 3: Explain hoisting in JavaScript.

Hoisting moves variable and function declarations to the top of their scope before code execution. var variables are hoisted and initialized as undefined, while let and const are hoisted but not initialized (Temporal Dead Zone).

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

Question 4: What is the result of 3 + 2 + "7"?

The result is "57". JavaScript evaluates left to right: 3 + 2 is 5, then 5 + "7" performs string concatenation resulting in "57".

Question 5: What are truthy and falsy values in JavaScript?

Falsy values are false, 0, -0, 0n, "", null, undefined, and NaN. All other values are truthy.

Question 6: Explain the difference between var, let, and const.

var has function scope and can be redeclared/reassigned. let and const have block scope. let can be reassigned, but const cannot after initial assignment.

if (true) {
  var a = 1;
  let b = 2;
  const c = 3;
}
console.log(a); // 1 (function scoped)
console.log(b); // ReferenceError

Question 7: What is strict mode in JavaScript?

Strict mode ('use strict') enforces stricter parsing and error handling, catching common coding errors like undeclared variables and duplicate parameters.

'use strict';
x = 5; // ReferenceError: x is not defined

Question 8: How do you create an object in JavaScript?

Objects can be created using object literals, Object.create(), new Object(), or ES6 classes.

const obj = {name: 'John'};
const obj2 = Object.create(null);
const obj3 = new Object();
class Person {}
const obj4 = new Person();

Question 9: What does this keyword refer to in different contexts?

In global scope, this refers to the window object (browser). In object methods, it refers to the object. In arrow functions, it inherits from the parent scope.

const obj = {
  name: 'JS',
  say() { console.log(this.name); } // 'JS'
};
obj.say();

Question 10: What is the output of console.log(typeof null)?

The output is "object". This is a historical bug in JavaScript where null was incorrectly identified as an object.

Intermediate JavaScript Interview Questions (1-3 Years Experience)

Question 11: Explain closures in JavaScript.

A closure is a function that retains access to variables from its outer scope even after the outer function has returned. Closures are commonly used for data privacy and function factories.

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

Question 12: What is event bubbling and how to stop it?

Event bubbling is when an event triggers handlers on parent elements after the target element. Use event.stopPropagation() to prevent it.

element.addEventListener('click', function(e) {
  e.stopPropagation();
});

Question 13: Explain the difference between null and undefined.

undefined means a variable has been declared but not assigned. null is an intentional assignment representing no value. typeof undefined is 'undefined', while typeof null is 'object'.

Question 14: What are arrow functions and their limitations?

Arrow functions provide concise syntax and lexically bind this. They cannot be used as constructors and lack their own this, arguments, or super.

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

Question 15: How does Object.keys(), Object.values(), and Object.entries() work?

Object.keys() returns an array of property names. Object.values() returns property values. Object.entries() returns key-value pairs as arrays.

const obj = {a: 1, b: 2};
console.log(Object.keys(obj));     // ['a', 'b']
console.log(Object.values(obj));   // [1, 2]
console.log(Object.entries(obj));  // [['a', 1], ['b', 2]]

Question 16: What is the difference between call(), apply(), and bind()?

All change function this context. call() and apply() execute immediately (apply() takes array arguments). bind() returns a new function without executing.

function greet(greeting) {
  console.log(greeting + ' ' + this.name);
}
greet.call({name: 'John'}, 'Hi'); // Hi John

Question 17: Explain prototypal inheritance.

JavaScript uses prototypes for inheritance. Objects inherit properties from their prototype. The prototype chain continues until null is reached.

function Animal() {}
Animal.prototype.speak = function() {};
const dog = new Animal();
console.log(dog.speak === Animal.prototype.speak); // true

Question 18: What is currying in JavaScript?

Currying transforms a function with multiple arguments into a sequence of functions each taking a single argument. It’s useful for partial application.

function add(a) {
  return function(b) {
    return a + b;
  };
}
const add5 = add(5);
console.log(add5(3)); // 8

Advanced JavaScript Interview Questions (3-6 Years Experience)

Question 19: Explain the event loop in JavaScript.

The event loop handles asynchronous operations. The call stack executes synchronous code first. Async callbacks go to the task queue and are processed when the stack is empty.

Question 20: What is a Promise and how do you handle Promise chains?

A Promise represents an asynchronous operation with states: pending, fulfilled, or rejected. Use .then(), .catch(), and .finally() for chaining.

new Promise((resolve) => {
  setTimeout(() => resolve('Done'), 1000);
}).then(result => console.log(result));

Question 21: Explain async/await syntax.

async/await provides cleaner asynchronous code. async functions return Promises. await pauses execution until the Promise settles.

async function fetchData() {
  try {
    const data = await fetch('api/data');
    return data.json();
  } catch (error) {
    console.error(error);
  }
}

Question 22: What is debouncing and how to implement it?

Debouncing limits function execution frequency, useful for search inputs or scroll events. It delays execution until a specified time passes without calls.

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

Question 23: How do you implement error handling in asynchronous code?

Use try-catch with async/await or .catch() with Promises. Global error handling uses window.onerror or unhandled rejection handlers.

window.addEventListener('unhandledrejection', (e) => {
  console.error('Unhandled promise rejection:', e.reason);
});

Question 24: Explain the Temporal Dead Zone (TDZ).

TDZ is the period between entering a scope and a let/const variable declaration. Accessing variables in TDZ throws ReferenceError.

console.log(a); // ReferenceError (TDZ)
let a = 5;

Question 25: What are generators and how do they work?

Generators are functions that pause/resume execution using yield. They return iterator objects for controlled data production.

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

Question 26: How would you deep clone an object in JavaScript?

Use structuredClone() (modern), JSON.parse(JSON.stringify()) (simple objects), or recursive functions for complex objects with functions/dates.

function deepClone(obj) {
  if (obj === null || typeof obj !== 'object') return obj;
  const clone = Array.isArray(obj) ? [] : {};
  for (let key in obj) {
    clone[key] = deepClone(obj[key]);
  }
  return clone;
}

Question 27: Explain Proxy objects and their use cases.

Proxy wraps objects to intercept operations like property access. Useful for validation, logging, or reactive systems.

const target = {name: 'John'};
const handler = {
  get(target, prop) {
    return target[prop] ? target[prop] : 'Not found';
  }
};
const proxy = new Proxy(target, handler);
console.log(proxy.age); // 'Not found'

Question 28: What is memoization and how to implement it?

Memoization caches function results for given arguments to avoid recomputation. Useful for expensive operations.

function memoize(fn) {
  const cache = {};
  return function(...args) {
    const key = JSON.stringify(args);
    return cache[key] || (cache[key] = fn.apply(this, args));
  };
}

Question 29: At Atlassian, how would you optimize a search input that triggers API calls on every keystroke?

Implement debouncing to limit API calls. Combine with caching to store recent search results and avoid duplicate requests.

Question 30: For a Paytm-like application, explain strategies to handle race conditions in concurrent API requests.

Use AbortController to cancel outdated requests, Promise.race() for timeouts, or sequence requests with async/await. Track request IDs to ignore stale responses.

Leave a Reply

Your email address will not be published. Required fields are marked *