JavaScript

Top 20 JavaScript Interview Questions and Answers in 2026

The most commonly asked JavaScript interview questions in 2026, with clear answers and code examples to help you land your next developer job.

May 13, 202610 min read
Share
Advertisement (not configured)

How to Use This Guide

These are the 20 most commonly asked JavaScript interview questions in 2026. For each question, I give you the short answer first, then the full explanation with a code example. Read through all of them once, then focus on the ones you cannot answer confidently.


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

Short answer: var is function-scoped and can be re-declared. let and const are block-scoped. const cannot be reassigned.

var x = 1;
var x = 2; // OK — var can be re-declared

let y = 1;
// let y = 2; // Error — cannot re-declare let

const z = 1;
// z = 2; // Error — cannot reassign const

// Block scope example
if (true) {
    var a = 'var';   // accessible outside block
    let b = 'let';   // only accessible inside block
    const c = 'const'; // only accessible inside block
}
console.log(a); // 'var'
// console.log(b); // ReferenceError

Rule of thumb: Always use const. Use let only when you need to reassign. Never use var.


2. What is a closure?

Short answer: A closure is a function that remembers the variables from its outer scope even after the outer function has finished executing.

function makeCounter() {
    let count = 0; // This variable is "closed over"

    return function() {
        count++;
        return count;
    };
}

const counter = makeCounter();
console.log(counter()); // 1
console.log(counter()); // 2
console.log(counter()); // 3

count is not accessible from outside makeCounter, but the returned function remembers it. This is a closure.


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

Short answer: == compares values with type coercion. === compares values AND types without coercion. Always use ===.

console.log(1 == '1');   // true  (type coercion converts '1' to 1)
console.log(1 === '1');  // false (different types)

console.log(0 == false);  // true
console.log(0 === false); // false

console.log(null == undefined);  // true
console.log(null === undefined); // false

4. What is event delegation?

Short answer: Event delegation means attaching one event listener to a parent element instead of many listeners on each child element.

// Bad — adds 100 event listeners
document.querySelectorAll('.btn').forEach(btn => {
    btn.addEventListener('click', handleClick);
});

// Good — adds 1 event listener on the parent
document.querySelector('#container').addEventListener('click', (e) => {
    if (e.target.matches('.btn')) {
        handleClick(e);
    }
});

This is more efficient and works for dynamically added elements too.


5. What is the difference between null and undefined?

Short answer: undefined means a variable has been declared but not assigned. null means deliberately no value.

let a;
console.log(a); // undefined — declared but no value

let b = null;
console.log(b); // null — intentionally empty

console.log(typeof undefined); // 'undefined'
console.log(typeof null);      // 'object' (a known JavaScript bug)

6. What are Promises and how do they work?

Short answer: A Promise represents an asynchronous operation that will either resolve (success) or reject (failure) in the future.

function fetchUser(id) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            if (id > 0) {
                resolve({ id, name: 'Ahmed' });
            } else {
                reject(new Error('Invalid ID'));
            }
        }, 1000);
    });
}

// Using .then/.catch
fetchUser(1)
    .then(user => console.log(user))
    .catch(err => console.error(err));

// Using async/await (cleaner)
async function main() {
    try {
        const user = await fetchUser(1);
        console.log(user);
    } catch (err) {
        console.error(err);
    }
}

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

Short answer: All three set the this context. call passes arguments one by one, apply passes as an array, bind returns a new function.

function greet(greeting, punctuation) {
    return `${greeting}, ${this.name}${punctuation}`;
}

const user = { name: 'Ahmed' };

greet.call(user, 'Hello', '!');      // 'Hello, Ahmed!'
greet.apply(user, ['Hello', '!']);   // 'Hello, Ahmed!'

const boundGreet = greet.bind(user);
boundGreet('Hello', '!');            // 'Hello, Ahmed!'

8. What is the event loop?

Short answer: The event loop allows JavaScript to perform non-blocking operations despite being single-threaded. It processes the call stack, then the microtask queue (Promises), then the macrotask queue (setTimeout).

console.log('1');

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

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

console.log('4');

// Output: 1, 4, 3, 2
// Synchronous first → Promise microtask → setTimeout macrotask

9. What is destructuring?

Short answer: Destructuring extracts values from arrays or objects into variables.

// Object destructuring
const user = { name: 'Ahmed', age: 25, city: 'Karachi' };
const { name, age } = user;

// With rename
const { name: userName } = user;

// Array destructuring
const [first, second, ...rest] = [1, 2, 3, 4, 5];
console.log(first); // 1
console.log(rest);  // [3, 4, 5]

// In function parameters
function display({ name, age = 18 }) {
    console.log(`${name} is ${age}`);
}
display(user);

10. What is the spread operator?

Short answer: The spread operator (...) expands an array or object into individual elements.

// Merge arrays
const a = [1, 2, 3];
const b = [4, 5, 6];
const merged = [...a, ...b]; // [1, 2, 3, 4, 5, 6]

// Copy and update object
const user = { name: 'Ahmed', role: 'admin' };
const updated = { ...user, role: 'viewer' }; // replaces role

// Pass array as function arguments
function sum(x, y, z) { return x + y + z; }
const nums = [1, 2, 3];
sum(...nums); // 6

11. What is hoisting?

Short answer: Hoisting moves var declarations and function declarations to the top of their scope before execution. let and const are not hoisted in the same way.

console.log(x); // undefined (not an error — var is hoisted)
var x = 5;

// console.log(y); // ReferenceError — let is not accessible before declaration
let y = 5;

// Function declarations are fully hoisted
sayHello(); // Works!
function sayHello() { console.log('Hello'); }

// Function expressions are NOT hoisted
// greet(); // TypeError
const greet = function() { console.log('Hi'); };

12. What is this in JavaScript?

Short answer: this refers to the object that is calling the function. In the browser's global scope, this is window. In arrow functions, this is inherited from the surrounding scope.

const obj = {
    name: 'Ahmed',
    regular: function() {
        console.log(this.name); // 'Ahmed' — this is obj
    },
    arrow: () => {
        console.log(this.name); // undefined — arrow inherits outer this
    }
};

13. What is the difference between map, filter, and reduce?

const numbers = [1, 2, 3, 4, 5];

// map — transform each element, returns same length array
const doubled = numbers.map(n => n * 2);
// [2, 4, 6, 8, 10]

// filter — keep elements that pass the test
const evens = numbers.filter(n => n % 2 === 0);
// [2, 4]

// reduce — accumulate into a single value
const sum = numbers.reduce((total, n) => total + n, 0);
// 15

14. What is optional chaining (?.)?

Short answer: Optional chaining safely accesses nested properties without throwing an error if something in the chain is null or undefined.

const user = { address: { city: 'Karachi' } };

// Old way — error-prone
const city = user && user.address && user.address.city;

// New way
const city2 = user?.address?.city; // 'Karachi'
const zip = user?.address?.zip;    // undefined (no error)
const len = user?.getName?.();     // undefined (no error)

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

// Synchronous — blocks until done
function syncTask() {
    const result = heavyCalculation(); // blocks for 5 seconds
    console.log(result);
}

// Asynchronous — does not block
async function asyncTask() {
    const result = await fetch('/api/data'); // does not block
    const data = await result.json();
    console.log(data);
}

JavaScript is single-threaded, so long synchronous operations freeze the browser. Use async/await for any operation that involves waiting — API calls, file reading, timers.


Quick Reference: Most Asked Topics

Topic Frequency in Interviews
var vs let vs const Very High
Closures Very High
Promises / async-await Very High
Event loop High
this keyword High
Destructuring High
Array methods High
Hoisting Medium
Event delegation Medium
Optional chaining Medium

How to Prepare

  1. Write code by hand for every question above — typing it yourself makes it stick
  2. Explain each concept out loud as if teaching someone else
  3. Build small examples in your browser console
  4. Review the ones you got wrong the night before your interview

These 15 questions cover 80% of what you'll be asked in a JavaScript interview. Master them and you will walk in confident.

Advertisement (not configured)

Written by

Raretechsol

Software company from Pakistan, specializing in Python and JavaScript. Passionate about automation, AI, and building practical web applications.

Related Articles