JavaScript Interview Guide

41 Core Questions, Definitions & Practical Code Examples

JavaScript Fundamentals

1. What is JavaScript?

Fundamentals

Answer: JavaScript is a high-level programming language mainly used to make web pages interactive and dynamic. It can run in browsers and also on servers using environments such as Node.js.

console.log("Hello, World!");

2. var vs let vs const

Fundamentals

Answer: var is function-scoped and can be redeclared. let is block-scoped and can be reassigned. const is block-scoped and cannot be reassigned after initialization.[cite: 1]

let age = 20;
age = 21;

const name = 'Ali';
// name = 'Sufiyan'; // Error: Assignment to constant variable.

3. Data Types

Fundamentals

Answer: Primitive types include string, number, bigint, boolean, undefined, null, and symbol. Objects, arrays, and functions are non-primitive/reference values.[cite: 1]

const str = "Text"; // String (Primitive)
const num = 100;    // Number (Primitive)
const obj = { id: 1 }; // Object (Reference)

4. == vs ===

Fundamentals

Answer: == performs type coercion before comparison, while === compares both value and type without coercion. In interviews and production code, === is generally preferred.[cite: 1]

console.log(5 == '5');  // true (Type Coercion)
console.log(5 === '5'); // false (Strict Type Check)

5. What is undefined?

Fundamentals

Answer: undefined usually means a variable has been declared but has not been assigned a value, or a requested property does not exist.[cite: 1]

let x;
console.log(x); // undefined

6. What is null?

Fundamentals

Answer: null is an intentional absence of a value. It is commonly assigned when you deliberately want to represent 'no value'.[cite: 1]

let user = null; // Deliberately set to no value

7. What is NaN?

Fundamentals

Answer: NaN means Not-a-Number. It is a special numeric value produced by invalid numeric operations.[cite: 1]

console.log(Number('hello')); // NaN

8. Primitive vs Reference Values

Fundamentals

Answer: Primitive values are simple immutable values. Objects and arrays are reference values, so variables can refer to the same underlying object.[cite: 1]

let p1 = 10;
let p2 = p1; // Value copied

let obj1 = { val: 10 };
let obj2 = obj1; // Reference shared
Functions, Scope & Closures

9. What is a function?

Functions

Answer: A function is a reusable block of code designed to perform a specific task. It can receive parameters and return a value.[cite: 1]

function greet(name) {
    return `Hello, ${name}`;
}

10. What is an arrow function?

Functions

Answer: An arrow function is a shorter function syntax. It also handles this differently because it does not create its own this.[cite: 1]

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

11. What is scope?

Scope

Answer: Scope determines where a variable can be accessed. Common JavaScript scopes are global, function, and block scope.[cite: 1]

if (true) {
    let blockScoped = "Inside Block";
}
// console.log(blockScoped); // ReferenceError

12. What is lexical scope?

Scope

Answer: Lexical scope means a function can access variables based on where the function was written in the source code.[cite: 1]

const outerVar = "I am outside";
function inner() {
    console.log(outerVar); // Accesses outer scope
}

13. What is hoisting?

Scope

Answer: Hoisting is JavaScript's behavior of processing declarations before code execution. var declarations are initialized as undefined, while let and const remain in the temporal dead zone until initialized.[cite: 1]

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

14. What is a closure?

Closures

Answer: A closure occurs when a function remembers and can access variables from its outer lexical scope even after the outer function has finished executing.[cite: 1]

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

15. What is a callback function?

Functions

Answer: A callback is a function passed to another function so it can be executed later or when an operation completes.[cite: 1]

function processUser(name, callback) {
    callback(`User: ${name}`);
}
processUser("Ali", console.log);

16. What is a higher-order function?

Functions

Answer: A higher-order function accepts another function as an argument, returns a function, or both.[cite: 1]

const multiplyBy = (factor) => (number) => number * factor;
const double = multiplyBy(2);
console.log(double(5)); // 10
Arrays & Objects

17. What is map()?

Array Methods

Answer: map() creates a new array by transforming every element of the original array.[cite: 1]

const doubled = [1, 2, 3].map(n => n * 2);
console.log(doubled); // [2, 4, 6]

18. What is filter()?

Array Methods

Answer: filter() creates a new array containing only elements that satisfy a condition.[cite: 1]

const evens = [1, 2, 3, 4].filter(n => n % 2 === 0);
console.log(evens); // [2, 4]

19. What is reduce()?

Array Methods

Answer: reduce() processes an array and combines its elements into a single accumulated result, such as a sum or object.[cite: 1]

const sum = [1, 2, 3].reduce((acc, n) => acc + n, 0);
console.log(sum); // 6

20. map() vs forEach()?

Array Methods

Answer: map() returns a new array and is used for transformation. forEach() does not return a transformed array and is commonly used for side effects.[cite: 1]

const a = [1, 2].map(x => x * 2); // [2, 4]
const b = [1, 2].forEach(x => console.log(x)); // undefined

21. What is destructuring?

Objects & Arrays

Answer: Destructuring extracts values from arrays or properties from objects into variables.[cite: 1]

const user = { name: 'Ali', age: 20 };
const { name, age } = user;
console.log(name, age); // 'Ali', 20

22. What is the spread operator?

ES6+

Answer: The spread operator (...) expands iterable values or object properties, commonly used to copy or combine arrays and objects.[cite: 1]

const a = [1, 2];
const b = [...a, 3]; // [1, 2, 3]

23. What is the rest parameter?

ES6+

Answer: The rest parameter collects multiple arguments into an array.[cite: 1]

function sum(...nums) {
    return nums.reduce((a, b) => a + b, 0);
}
console.log(sum(1, 2, 3)); // 6
Asynchronous JavaScript

24. What is a Promise?

Async JS

Answer: A Promise represents the eventual result of an asynchronous operation. It can be pending, fulfilled, or rejected.[cite: 1]

const myPromise = new Promise((resolve, reject) => {
    resolve("Success!");
});

25. What is async/await?

Async JS

Answer: async/await is syntax built on Promises that makes asynchronous code easier to read and write. An async function returns a Promise.[cite: 1]

async function getData() {
    const res = await fetch('/api/users');
    return res.json();
}

26. What is the event loop?

Architecture

Answer: The event loop coordinates synchronous code, the call stack, and queued asynchronous callbacks so JavaScript can handle non-blocking operations.[cite: 1]

console.log("Start");
setTimeout(() => console.log("Async Task"), 0);
console.log("End");

27. What is the call stack?

Architecture

Answer: The call stack is the structure JavaScript uses to keep track of currently executing function calls.[cite: 1]

function first() { second(); }
function second() { console.log("Stack execution"); }
first();

28. What are Web APIs?

Browser

Answer: In browsers, Web APIs such as fetch, timers, and DOM APIs are provided by the browser environment rather than by the JavaScript language itself.[cite: 1]

setTimeout(() => {}, 1000); // Web API Timer

29. Microtask vs Macrotask?

Architecture

Answer: Promise callbacks are microtasks and are generally processed before timer callbacks such as setTimeout callbacks after the current stack is empty.[cite: 1]

Promise.resolve().then(() => console.log("Microtask"));
setTimeout(() => console.log("Macrotask"), 0);

30. Error handling with async/await?

Async JS

Answer: Use try/catch around awaited operations and handle expected failures appropriately.[cite: 1]

try {
    const data = await getData();
} catch (error) {
    console.error(error);
}
DOM, Events & Storage

31. What is the DOM?

DOM

Answer: The Document Object Model is a tree-like representation of an HTML document that JavaScript can read and modify.[cite: 1]

document.getElementById('title').innerText = "Hello";

32. What is event bubbling?

Events

Answer: Event bubbling means an event starts at the target element and then propagates upward through its ancestors.[cite: 1]

elem.addEventListener('click', handler); // Bubbles up

33. What is event delegation?

Events

Answer: Event delegation attaches one handler to a parent and uses event propagation to handle events from its children, reducing the number of handlers.[cite: 1]

parent.addEventListener('click', (e) => {
    if (e.target.matches('button')) { /* handle */ }
});

34. localStorage vs sessionStorage?

Storage

Answer: localStorage persists data until it is removed, while sessionStorage normally lasts for the current browser tab/session.[cite: 1]

localStorage.setItem('key', 'value');
sessionStorage.setItem('tempKey', 'value');

35. What is JSON?

Data

Answer: JSON is a text format commonly used to exchange structured data. JSON.stringify converts a JavaScript value to JSON text, and JSON.parse converts JSON text back to a JavaScript value.[cite: 1]

const str = JSON.stringify({ a: 1 });
const obj = JSON.parse(str);
Interview-Level Concepts

36. What is 'this' in JavaScript?

Advanced

Answer: this refers to a value determined by how a function is called. Arrow functions do not create their own this and instead use the surrounding lexical this.[cite: 1]

const obj = {
    name: "Sufiyan",
    show() { console.log(this.name); }
};

37. Shallow Copy vs Deep Copy?

Advanced

Answer: A shallow copy duplicates only the top-level structure, while nested objects may still be shared. A deep copy duplicates nested structures as well.[cite: 1]

const shallow = { ...original };
const deep = structuredClone(original);

38. What is debouncing?

Optimization

Answer: Debouncing delays execution until a specified period has passed without another triggering event, useful for search inputs and resize events.[cite: 1]

// Delays function call until user stops typing

39. What is throttling?

Optimization

Answer: Throttling limits how often a function can execute during a period, useful for scroll or mousemove events.[cite: 1]

// Executes function at most once every N milliseconds

40. What are ES6 features?

ES6+

Answer: ES6 introduced important features such as let/const, arrow functions, classes, template literals, destructuring, modules, default parameters, spread/rest, and Promises.[cite: 1]

const template = `Hello ${user}`;

41. What is a module?

ES6 Modules

Answer: A module is a JavaScript file whose values can be explicitly exported and imported, helping organize code and manage dependencies.[cite: 1]

export const add = (a, b) => a + b;
import { add } from './math.js';