Posted in

Top 30 JavaScript Interview Questions and Answers for All Levels

Prepare for Your JavaScript Interview with Basic to Advanced Questions

Master JavaScript interview preparation with these 30 carefully curated questions covering basic, intermediate, and advanced topics. Perfect for freshers, developers with 1-3 years experience, and professionals with 3-6 years of experience. Each question includes clear explanations and practical code examples.

Basic JavaScript Interview Questions (Freshers & 0-1 Year Experience)

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

== performs type coercion before comparison, while === compares both value and type without coercion.

console.log(5 == '5');   // true (type coercion)
console.log(5 === '5');  // false (strict comparison)

2. What are the different data types in JavaScript?

JavaScript has 8 data types: 7 primitives (String, Number, BigInt, Boolean, undefined, null, Symbol) and 1 non-primitive (Object).

3. What is the result of 3 + 2 + "7"?

The result is "57". Numbers add first (3+2=5), then concatenate with string (“5″+”7″=”57”).

console.log(3 + 2 + "7"); // "57"

4. Explain hoisting in JavaScript.

Hoisting moves variable and function declarations to the top of their scope before code execution, but not initializations.

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

5. What are truthy and falsy values in JavaScript?

Falsy values: false, 0, -0, 0n, “”, null, undefined, NaN. All others are truthy.

6. What is the difference between var, let, and const?

var x = 10;  // function scoped, hoisted
let y = 20;  // block scoped, not hoisted
const z = 30; // block scoped, cannot be reassigned

7. What does typeof operator return?

Returns a string indicating the type of operand: “number”, “string”, “boolean”, “object”, “undefined”, “function”, “symbol”, “bigint”.

8. How do you create an object in JavaScript?

// Object literal
const obj = {name: "John", age: 25};

// Object constructor
const obj2 = new Object({name: "Jane"});

// Object.create()
const obj3 = Object.create({name: "Bob"});

Intermediate JavaScript Interview Questions (1-3 Years Experience)

9. What is closure in JavaScript?

A closure is a function that retains access to its outer scope even after the outer function has returned.

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

10. Explain this keyword in different contexts at Zoho.

// Global context
console.log(this); // Window object

// Object method
const obj = {name: "Zoho", show: function() {console.log(this.name)}};
obj.show(); // "Zoho"

// Arrow function (lexical this)
const arrow = {name: "Zoho", show: () => console.log(this.name)};
arrow.show(); // undefined

11. What is event bubbling and capturing?

Bubbling: events propagate from target to root. Capturing: events propagate from root to target. Use addEventListener(event, handler, true) for capturing.

12. How does async/await work?

async functions return Promises. await pauses execution until Promise resolves.

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

13. What are Promises and their states?

Promises have three states: pending, fulfilled (resolved), rejected. Use .then(), .catch(), .finally().

14. Explain array methods: map, filter, reduce.

const numbers = [1, 2, 3, 4];
// map - transform
const doubled = numbers.map(n => n * 2); // [2, 4, 6, 8]
// filter - condition
const evens = numbers.filter(n => n % 2 === 0); // [2, 4]
// reduce - accumulate
const sum = numbers.reduce((acc, n) => acc + n, 0); // 10

15. What is debouncing in JavaScript?

Debouncing delays function execution until after a wait period has elapsed since the last invocation. Useful for search inputs, scroll events.

Advanced JavaScript Interview Questions (3-6 Years Experience)

16. What is the event loop in JavaScript?

Event loop handles async operations. Call stack → Task queue → Microtask queue → Render. Processes callbacks and promises.

17. Explain prototypal inheritance.

Objects inherit properties from other objects via prototype chain. Every object has __proto__ pointing to its prototype.

function Animal(name) {
  this.name = name;
}
Animal.prototype.speak = function() {
  console.log(this.name + " makes a sound");
};
const dog = new Animal("Rex");
dog.speak(); // "Rex makes a sound"

18. What are generators in JavaScript?

Functions that can be paused and resumed using yield. Return iterator objects.

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

19. How does Proxy work in JavaScript?

Proxy wraps an object, intercepting operations like property access, assignment. Used for validation, logging.

const target = {name: "Paytm"};
const handler = {
  get(target, prop) {
    return target[prop] ? target[prop].toUpperCase() : undefined;
  }
};
const proxy = new Proxy(target, handler);
console.log(proxy.name); // "PAYTM"

20. What is strict mode in JavaScript?

Strict mode (“use strict”) enforces stricter parsing and error handling, catches common coding errors.

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

21. Explain Symbol data type.

Symbols are unique, immutable primitives for object keys. Prevents property name collisions.

const sym = Symbol("key");
const obj = {[sym]: "value"};
console.log(obj[sym]); // "value"

22. What are WeakMap and WeakSet?

WeakMap/WeakSet hold weak references to objects. Garbage collected when no other references exist. Keys must be objects.

23. How to deep clone an object?

const obj = {name: "Adobe", nested: {age: 25}};
const clone = JSON.parse(JSON.stringify(obj));
// Or structuredClone() in modern browsers
const clone2 = structuredClone(obj);

24. What is the temporal dead zone (TDZ)?

Block between let/const declaration and initialization where accessing variable throws ReferenceError.

25. Explain Object.keys(), Object.values(), Object.entries().

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

26. What is a higher-order function?

Function that takes another function as argument or returns a function. Examples: map, filter, reduce.

27. Scenario: Handle API errors at Salesforce using async/await.

async function fetchUserData(userId) {
  try {
    const response = await fetch(`/api/users/${userId}`);
    if (!response.ok) throw new Error("User not found");
    return await response.json();
  } catch (error) {
    console.error("API Error:", error.message);
    return null;
  }
}

28. Scenario: Implement a cache system at Atlassian using Map.

const cache = new Map();
function getData(key) {
  if (cache.has(key)) {
    console.log("Cache hit");
    return cache.get(key);
  }
  const data = computeExpensiveValue(key);
  cache.set(key, data);
  return data;
}

29. What is the difference between call, apply, bind?

function greet(greeting, name) {
  console.log(greeting + " " + name);
}
greet.call(null, "Hi", "Swiggy");     // Hi Swiggy
greet.apply(null, ["Hello", "Swiggy"]); // Hello Swiggy
const bound = greet.bind(null, "Hey"); // Returns function
bound("SAP"); // Hey SAP

30. How would you optimize performance for large DOM lists at Oracle?

Use DocumentFragment for batch DOM updates, virtual scrolling for large lists, requestAnimationFrame for smooth animations, debounce/ throttle event handlers.

const fragment = document.createDocumentFragment();
data.forEach(item => {
  const li = document.createElement('li');
  li.textContent = item;
  fragment.appendChild(li);
});
ul.appendChild(fragment);

Practice these questions regularly and understand the underlying concepts. Good luck with your JavaScript interviews at top companies like Amazon, Flipkart, and SAP!

Leave a Reply

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