Posted in

Top 30 JavaScript Interview Questions and Answers for All Levels

Prepare for your JavaScript interview with this comprehensive guide featuring 30 essential questions. Covering basic, intermediate, and advanced topics, these questions help freshers, developers with 1-3 years, and 3-6 years of experience build confidence and technical expertise.

Basic JavaScript Interview Questions (Freshers)

1. What are the different data types in JavaScript?

JavaScript has primitive data types: String, Number, BigInt, Boolean, Undefined, Symbol, and Null. It also has a non-primitive type called Object.

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

== performs type coercion before comparison, while === checks both value and type without coercion. Example: 5 == '5' is true, but 5 === '5' is false.

3. What is hoisting in JavaScript?

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

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

4. What is the difference between null and undefined?

undefined means a variable has been declared but not assigned. null is an intentional assignment representing no value.

5. What are the differences between var, let, and const?

var has function scope and can be redeclared. let and const have block scope. let can be reassigned, const cannot.

let x = 10;
x = 20; // OK
const y = 30;
// y = 40; // Error

6. What are truthy and falsy values in JavaScript?

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

7. What is a callback function?

A callback is a function passed as an argument to another function and executed after some operation completes.

function greet(name, callback) {
    console.log('Hi ' + name);
    callback();
}

8. What is the purpose of setTimeout()?

setTimeout() executes a function after a specified delay in milliseconds. It returns a timer ID that can be used to cancel it.

9. How do you check if an array contains a value?

Use the includes() method: arr.includes(value). It returns true if the value exists, false otherwise.

10. How do you remove duplicates from an array?

Use Set with spread operator: [...new Set(array)].

const arr = [1, 2, 2, 3];
const unique = [...new Set(arr)]; // [1, 2, 3]

Intermediate JavaScript Interview Questions (1-3 Years Experience)

11. What are closures in JavaScript?

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

function outer() {
    let count = 0;
    return function inner() {
        count++;
        return count;
    };
}

12. What are Promises in JavaScript?

Promises represent asynchronous operations with states: pending, fulfilled, or rejected. They enable chaining with .then() and .catch().

13. What is the purpose of async and await?

async makes a function return a Promise. await pauses execution until the Promise resolves, making async code look synchronous.

async function fetchData() {
    const data = await fetch('url');
    return data.json();
}

14. What are arrow functions?

Arrow functions provide concise syntax and do not have their own this binding. They inherit this from the enclosing scope.

const add = (a, b) => a + b;

15. Explain event bubbling and capturing.

Bubbling: events propagate from target to root. Capturing: events propagate from root to target. Use addEventListener with {capture: true} for capturing.

16. What is destructuring in JavaScript?

Destructuring extracts values from arrays/objects into variables.

const {name, age} = {name: 'John', age: 30};
const [first, second] = [1, 2, 3];

17. What is the this keyword?

this refers to the object executing the current function. Context depends on how the function is called (global, object method, etc.).

18. How do you merge two objects?

Use spread operator: {...obj1, ...obj2} or Object.assign(target, source).

19. What is strict mode in JavaScript?

Strict mode ("use strict";) enforces stricter parsing and error handling, eliminating silent errors and unsafe practices.

20. Explain Object.keys(), Object.values(), and Object.entries().

Object.keys() returns property names array. Object.values() returns values array. Object.entries() returns [key, value] pairs array.

Advanced JavaScript Interview Questions (3-6 Years Experience)

21. What is a generator function?

Generator functions can pause and resume execution using yield, producing multiple values over time.

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

22. Explain prototypal inheritance.

Objects inherit properties/methods from other objects via prototype chain. Each object has a __proto__ linking to its prototype.

23. What is the event loop?

The event loop handles async operations by processing the call stack, task queue, and microtask queue to manage JavaScript’s single-threaded execution.

24. How does debouncing work in JavaScript?

Debouncing delays function execution until after a wait period from the last invocation, useful for optimizing search inputs or scroll events.

function debounce(fn, delay) {
    let timeout;
    return function() {
        clearTimeout(timeout);
        timeout = setTimeout(fn, delay);
    };
}

25. What are modules in JavaScript?

ES6 modules use export and import for code organization and reusability.

// math.js
export const add = (a, b) => a + b;

// main.js
import { add } from './math.js';

26. Explain error handling in async code.

Use try...catch with async/await or .catch() with Promises. Also use window.onerror for global errors.

27. What is a WeakMap and WeakSet?

WeakMap and WeakSet hold weak references to objects, allowing garbage collection when keys/objects are no longer referenced.

28. How do you implement private variables in JavaScript?

Use closures, WeakMaps, or ES2022 private fields (#privateVar).

class MyClass {
    #private = 'secret';
    getPrivate() { return this.#private; }
}

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

TDZ is the period between entering a scope and a let/const variable declaration, where accessing them throws ReferenceError.

30. In a Salesforce scenario, how would you handle API rate limiting with JavaScript?

Implement debouncing and exponential backoff with Promises and retry logic to respect rate limits while ensuring reliable API calls.

async function apiCallWithRetry(url, maxRetries = 3) {
    for (let i = 0; i < maxRetries; i++) {
        try {
            return await fetch(url);
        } catch (error) {
            await new Promise(resolve => setTimeout(resolve, 2 ** i * 1000));
        }
    }
}

Leave a Reply

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