JavaScript

JavaScript

Top Interview Questions

About JavaScript

 

JavaScript: The Language of the Modern Web

JavaScript is one of the most important and widely used programming languages in the world today. It plays a central role in making websites interactive, dynamic, and user-friendly. Alongside HTML and CSS, JavaScript forms the foundation of modern web development. While HTML structures web pages and CSS styles them, JavaScript adds behavior and logic, allowing websites to respond to user actions. Over time, JavaScript has evolved far beyond its original purpose and is now used in web applications, mobile apps, desktop software, and even server-side development.

JavaScript was created in 1995 by Brendan Eich while working at Netscape. Surprisingly, it was developed in just ten days. Despite its name, JavaScript is not directly related to Java, which often confuses beginners. The name was chosen mainly for marketing reasons because Java was popular at the time. Initially, JavaScript was designed to be a simple scripting language for adding basic interactions to web pages, such as form validation and button clicks. However, as the internet grew, so did the capabilities and importance of JavaScript.

One of the biggest strengths of JavaScript is that it runs directly in the web browser. This means users do not need to install additional software to use JavaScript-powered websites. When a user opens a webpage, the browser reads the JavaScript code and executes it instantly. This allows web pages to update content without reloading, show animations, display alerts, and respond to user input in real time. Features such as dropdown menus, image sliders, and interactive maps all rely heavily on JavaScript.

JavaScript is known as a high-level and interpreted programming language. Being high-level means it is closer to human language than machine language, making it easier to learn and write. Being interpreted means the code is executed line by line rather than being compiled first. JavaScript is also dynamically typed, which means developers do not need to declare variable types explicitly. While this flexibility makes development faster, it also requires careful coding to avoid errors.

Another important concept in JavaScript is event-driven programming. Events are actions that occur when a user interacts with a webpage, such as clicking a button, typing in a text box, or moving the mouse. JavaScript listens for these events and runs specific code in response. This makes websites feel interactive and responsive rather than static. For example, when a user submits a form, JavaScript can instantly check if the input is valid and show an error message without refreshing the page.

As JavaScript grew in popularity, developers began creating libraries and frameworks to make development easier and more efficient. Libraries like jQuery simplified complex tasks such as manipulating the Document Object Model (DOM), handling events, and making network requests. Later, powerful frameworks such as React, Angular, and Vue.js changed how developers build web applications. These frameworks allow developers to create large, complex applications with reusable components, better organization, and improved performance.

JavaScript is no longer limited to the browser. With the introduction of Node.js in 2009, JavaScript became a server-side language as well. Node.js allows developers to run JavaScript on servers, enabling them to build full-stack applications using a single programming language. This was a major breakthrough, as developers could now use JavaScript for both frontend and backend development. Companies like Netflix, PayPal, and LinkedIn use Node.js to handle large-scale applications efficiently.

Another area where JavaScript has expanded is mobile and desktop app development. Frameworks like React Native allow developers to build mobile apps for Android and iOS using JavaScript. Similarly, tools like Electron enable the creation of desktop applications for Windows, macOS, and Linux. Popular apps such as Discord, Visual Studio Code, and Slack are built using JavaScript-based technologies. This versatility makes JavaScript one of the most flexible programming languages available.

Despite its many advantages, JavaScript also has some challenges. Because it runs in the browser, it can be affected by security risks if not written carefully. Poorly written JavaScript code can lead to vulnerabilities such as cross-site scripting (XSS). Additionally, because different browsers may interpret JavaScript slightly differently, developers must test their code across multiple platforms to ensure consistent behavior. However, modern browsers and improved standards have reduced many of these issues.

Learning JavaScript is often recommended for beginners in programming. Its syntax is relatively simple, and beginners can quickly see results by running code in a browser. This immediate feedback makes learning more engaging and motivating. At the same time, JavaScript is powerful enough to support advanced concepts such as asynchronous programming, promises, and object-oriented design. As a result, learners can grow from beginner to advanced developer without needing to switch languages.

In conclusion, JavaScript is a cornerstone of modern technology and web development. From simple interactive websites to complex applications used by millions of people, JavaScript plays a crucial role in shaping the digital world. Its ability to run in browsers, servers, mobile devices, and desktops makes it incredibly versatile. While it has evolved significantly since its creation, JavaScript continues to grow and adapt to new technological demands. For anyone interested in programming or technology, understanding JavaScript is not just useful—it is essential.

Fresher Interview Questions

 

1. What is JavaScript?

Answer:
JavaScript is a high-level, interpreted programming language used to make web pages interactive.
It runs in the browser and allows you to:

  • Validate forms

  • Create dynamic content

  • Handle events (clicks, typing, etc.)

  • Build games, apps, and servers (with Node.js)

πŸ‘‰ JavaScript works together with HTML (structure) and CSS (design).


2. What are the features of JavaScript?

Answer:

  • Lightweight and fast

  • Interpreted (no compilation needed)

  • Object-based

  • Event-driven

  • Platform-independent

  • Supports functional programming


3. How is JavaScript different from Java?

Answer:

JavaScript Java
Interpreted language Compiled language
Used mainly for web Used for applications
Loosely typed Strongly typed
Runs in browser Runs on JVM

4. What are variables in JavaScript?

Answer:
Variables store data values. JavaScript has three ways to declare variables:

var x = 10;
let y = 20;
const z = 30;

Difference:

  • var → old, function-scoped

  • let → block-scoped

  • const → block-scoped, value cannot be changed


5. What are data types in JavaScript?

Answer:
JavaScript has two types of data types.

Primitive:

  • Number

  • String

  • Boolean

  • Undefined

  • Null

  • Symbol

  • BigInt

Non-Primitive:

  • Object

  • Array

  • Function

Example:

let name = "Alex";   // String
let age = 20;       // Number
let isStudent = true; // Boolean

6. What is undefined and null?

Answer:

  • undefined → variable declared but not assigned

  • null → intentional empty value

let a;
let b = null;

7. What is an operator?

Answer:
Operators perform operations on values.

Types:

  • Arithmetic: + - * / %

  • Assignment: = += -=

  • Comparison: == === !=

  • Logical: && || !


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

Answer:

  • == → compares values only

  • === → compares value and type

5 == "5"   // true
5 === "5"  // false

9. What are functions?

Answer:
Functions are reusable blocks of code.

function add(a, b) {
  return a + b;
}

10. What is an arrow function?

Answer:
Arrow functions are a shorter syntax for functions.

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

11. What is an array?

Answer:
An array stores multiple values in a single variable.

let colors = ["red", "blue", "green"];

12. What is an object?

Answer:
Objects store data as key-value pairs.

let student = {
  name: "John",
  age: 21
};

13. What is DOM?

Answer:
DOM (Document Object Model) represents the HTML structure of a webpage.
JavaScript uses DOM to:

  • Change HTML content

  • Modify styles

  • Handle events

Example:

document.getElementById("title").innerHTML = "Hello";

14. What is an event in JavaScript?

Answer:
An event is an action performed by the user.

Examples:

  • click

  • keypress

  • mouseover

button.onclick = function() {
  alert("Clicked!");
};

15. What is this keyword?

Answer:
this refers to the object that is currently calling the function.


16. What is hoisting?

Answer:
Hoisting moves variable and function declarations to the top of the scope.

console.log(x);
var x = 10;  // no error

17. What is a loop?

Answer:
Loops execute a block of code multiple times.

Types:

  • for

  • while

  • do-while

for (let i = 1; i <= 5; i++) {
  console.log(i);
}

18. What is NaN?

Answer:
NaN means Not a Number.

let result = "abc" / 10; // NaN

19. What is scope?

Answer:
Scope determines where variables can be accessed.

Types:

  • Global scope

  • Function scope

  • Block scope


20. What is callback function?

Answer:
A callback function is passed as an argument to another function.

function greet(name, callback) {
  callback();
}

 

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

Answer:

Feature var let const
Scope Function Block Block
Re-declare Yes No No
Re-assign Yes Yes No
Hoisting Yes (undefined) Yes (TDZ) Yes (TDZ)

Example:

let a = 10;
a = 20; // allowed

const b = 30;
b = 40; // error

22. What is a closure?

Answer:
A closure is a function that remembers variables from its outer scope, even after the outer function has finished execution.

Example:

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

let counter = outer();
counter(); // 1
counter(); // 2

23. What is the difference between null and undefined?

Answer:

null undefined
Assigned value Default value
Intentional empty Not initialized
Type is object Type is undefined

24. What is an IIFE?

Answer:
IIFE (Immediately Invoked Function Expression) runs as soon as it is defined.

(function () {
  console.log("IIFE executed");
})();

25. What is setTimeout()?

Answer:
Executes code after a specified delay.

setTimeout(() => {
  console.log("Hello after 2 seconds");
}, 2000);

26. What is setInterval()?

Answer:
Executes code repeatedly at a fixed time interval.

setInterval(() => {
  console.log("Repeats every second");
}, 1000);

27. What is the difference between synchronous and asynchronous JavaScript?

Answer:

  • Synchronous: Code executes line by line, blocking execution.

  • Asynchronous: Code executes without blocking.

Example:

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

28. What are promises?

Answer:
A Promise represents a value that will be available now, later, or never.

States:

  • Pending

  • Fulfilled

  • Rejected

Example:

let promise = new Promise((resolve, reject) => {
  resolve("Success");
});

29. What is async and await?

Answer:
Used to handle promises in a cleaner way.

async function fetchData() {
  let result = await fetch(url);
  console.log(result);
}

30. What is the event loop?

Answer:
The event loop handles asynchronous operations and executes them when the call stack is empty.


31. What is map()?

Answer:
map() creates a new array by modifying each element.

let nums = [1, 2, 3];
let squares = nums.map(n => n * n);

32. What is filter()?

Answer:
filter() returns elements that meet a condition.

let nums = [1, 2, 3, 4];
let even = nums.filter(n => n % 2 === 0);

33. What is reduce()?

Answer:
reduce() reduces an array to a single value.

let sum = nums.reduce((total, n) => total + n, 0);

34. What is the difference between map() and forEach()?

Answer:

map forEach
Returns new array Returns nothing
Used for transformation Used for iteration

35. What is JSON?

Answer:
JSON (JavaScript Object Notation) is used to store and transfer data.

Example:

{
  "name": "John",
  "age": 22
}

36. What is localStorage and sessionStorage?

Answer:

localStorage sessionStorage
Permanent Temporary
Data persists Cleared when tab closes
Storage limit ~5MB Storage limit ~5MB

37. What is this in arrow functions?

Answer:
Arrow functions do not have their own this.
They inherit this from the parent scope.


38. What is debouncing?

Answer:
Debouncing limits function execution until the user stops an action.

Example use case:

  • Search input

  • Window resize


39. What is throttling?

Answer:
Throttling limits function execution to once per time interval.


40. What is error handling in JavaScript?

Answer:
Handled using try...catch.

try {
  let x = y + 1;
} catch (error) {
  console.log(error);
}

41. What is strict mode?

Answer:
"use strict" enforces better coding practices.

"use strict";
x = 10; // error

42. What is type coercion?

Answer:
Automatic conversion of data types.

"5" + 2 // "52"
"5" - 2 // 3

43. What is the difference between shallow and deep copy?

Answer:

  • Shallow copy: Copies reference

  • Deep copy: Copies actual data

Example:

let copy = JSON.parse(JSON.stringify(obj));

44. What is a prototype?

Answer:
JavaScript uses prototypes for inheritance.


45. What is memory leak?

Answer:
Unused memory not released, often caused by:

  • Unremoved event listeners

  • Global variables

 

Experienced Interview Questions

 

1. Explain JavaScript execution context

Answer:
An execution context is the environment in which JavaScript code is evaluated.

Types:

  1. Global Execution Context

  2. Function Execution Context

  3. Eval Execution Context

Phases:

  1. Memory Creation Phase

    • Variables → undefined

    • Functions → stored fully

  2. Execution Phase

    • Code executes line by line

πŸ“Œ JavaScript is single-threaded and uses a call stack.


2. What is the call stack?

Answer:
The call stack is a data structure that tracks function execution.

  • LIFO (Last In, First Out)

  • Each function call creates a stack frame

Problem:

function a() { b(); }
function b() { c(); }
function c() {}

a();

Execution order:

a → b → c → pop c → pop b → pop a

3. Explain hoisting in detail

Answer:
Hoisting moves declarations to the top of scope.

Behavior:

  • var → hoisted with undefined

  • let / const → hoisted but in Temporal Dead Zone (TDZ)

  • Functions → fully hoisted

console.log(x); // undefined
var x = 10;
console.log(y); // ReferenceError
let y = 10;

4. What is Temporal Dead Zone (TDZ)?

Answer:
TDZ is the time between variable creation and initialization where access is not allowed.

console.log(a); // TDZ
let a = 10;

5. Explain closures with real-world use case

Answer:
A closure allows a function to access variables from its parent scope even after execution.

Use cases:

  • Data hiding

  • Memoization

  • Counters

  • Event handlers

Example:

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

const counter = createCounter();
counter(); // 1
counter(); // 2

6. What is the event loop?

Answer:
The event loop manages async operations.

Components:

  • Call Stack

  • Web APIs

  • Microtask Queue (Promises)

  • Callback Queue (setTimeout)

πŸ“Œ Microtasks have higher priority than callbacks

Order:

Call Stack → Microtasks → Callback Queue

7. Difference between setTimeout and Promises

Answer:

Feature setTimeout Promise
Queue Callback Microtask
Priority Lower Higher
Usage Delays Async logic

8. Explain this keyword

Answer:
this depends on how a function is called.

Cases:

  1. Global → window

  2. Object method → object

  3. Function → undefined (strict)

  4. Arrow function → lexical this

  5. Constructor → new object

const obj = {
  name: "JS",
  getName() {
    return this.name;
  }
};

9. Difference between arrow and normal functions

Answer:

Feature Arrow Normal
this Lexical Dynamic
arguments ❌ βœ…
constructor ❌ βœ…
hoisting ❌ βœ…

10. Explain deep copy vs shallow copy

Answer:

Shallow Copy:

  • Copies references

const copy = {...obj};

Deep Copy:

  • Copies actual values

const deep = structuredClone(obj);
// or
JSON.parse(JSON.stringify(obj));

11. What is prototype inheritance?

Answer:
JavaScript objects inherit properties via prototype chain.

function Person(name) {
  this.name = name;
}

Person.prototype.sayHello = function () {
  return "Hello " + this.name;
};

12. Explain call, apply, and bind

Answer:

func.call(obj, a, b);
func.apply(obj, [a, b]);
const newFunc = func.bind(obj);
Method Execution
call Immediate
apply Immediate
bind Later

13. What are higher-order functions?

Answer:
Functions that:

  • Take functions as arguments

  • Return functions

Examples:
map, filter, reduce


14. Explain map, filter, reduce

Answer:

arr.map(x => x * 2);       // transform
arr.filter(x => x > 10);  // condition
arr.reduce((a,b)=>a+b);   // accumulate

15. Explain currying

Answer:
Transforming a function with multiple arguments into nested functions.

const add = a => b => c => a + b + c;

16. What is debouncing?

Answer:
Executes function after user stops action.

Use cases:

  • Search input

  • Resize events


17. What is throttling?

Answer:
Executes function once per time interval.

Use cases:

  • Scroll events

  • Button clicks


18. Explain promises in depth

Answer:
Promise states:

  • Pending

  • Fulfilled

  • Rejected

fetch(url)
  .then(res => res.json())
  .catch(err => console.error(err));

19. What is async/await?

Answer:
Syntactic sugar over promises.

async function getData() {
  try {
    const res = await fetch(url);
  } catch (e) {}
}

20. Error handling strategies

Answer:

  • try/catch

  • Promise .catch

  • Global error handler

  • Custom errors


21. Explain memory leaks

Answer:
Occurs when memory is not released.

Causes:

  • Global variables

  • Event listeners not removed

  • Closures holding references

  • Timers not cleared


22. What is garbage collection?

Answer:
JavaScript automatically removes unused memory using mark-and-sweep algorithm.


23. Explain strict mode

Answer:

"use strict";

Benefits:

  • Prevents accidental globals

  • Throws more errors

  • Better performance


24. What is module system?

Answer:

  • ES6 modules

export default function(){}
import fn from "./file";

Benefits:

  • Encapsulation

  • Reusability

  • Tree shaking


25. How do you optimize JavaScript performance?

Answer:

  • Debounce/throttle

  • Avoid deep DOM access

  • Use async loading

  • Minimize re-renders

  • Use Web Workers


26. What is immutability?

Answer:
Data should not be modified directly.

const newArr = [...oldArr, 4];

27. Explain event delegation

Answer:
Handling events at parent instead of multiple children.

Benefits:

  • Better performance

  • Dynamic elements support


28. What are Web Workers?

Answer:
Run JS in background threads without blocking UI.


29. What is CORS?

Answer:
Security mechanism that controls cross-origin requests.


30. Difference between localStorage, sessionStorage, cookies

Answer:

Feature localStorage sessionStorage cookies
Size ~5MB ~5MB ~4KB
Expiry Permanent Tab close Custom
Server ❌ ❌ βœ…

 

31. Explain JavaScript memory management

Answer:
JavaScript uses automatic memory management.

Steps:

  1. Allocation – memory is allocated when variables are created

  2. Usage – memory used during execution

  3. Deallocation – garbage collector frees unused memory

Garbage Collection Algorithm:

  • Mark-and-Sweep

    • Reachable objects are marked

    • Unreachable objects are removed


32. What are weak references?

Answer:
Weak references allow objects to be garbage-collected.

Examples:

  • WeakMap

  • WeakSet

let wm = new WeakMap();
let obj = {};
wm.set(obj, "data");
obj = null; // eligible for GC

Use case:

  • Caching

  • Prevent memory leaks


33. Explain Object.freeze() vs Object.seal()

Answer:

Method Add Delete Modify
freeze ❌ ❌ ❌
seal ❌ ❌ βœ…
Object.freeze(obj);

34. Explain event propagation

Answer:
Event propagation has three phases:

  1. Capturing

  2. Target

  3. Bubbling

element.addEventListener("click", handler, true); // capture

35. What is event delegation?

Answer:
Handling child events via parent element.

Benefits:

  • Less memory usage

  • Handles dynamic elements


36. Explain the difference between microtask and macrotask

Answer:

Microtask Macrotask
Promise setTimeout
MutationObserver setInterval
Higher priority Lower priority

37. What happens if the call stack overflows?

Answer:
A stack overflow error occurs due to:

  • Infinite recursion

  • Excessive nested calls


38. Explain currying vs partial application

Answer:

Currying Partial
One arg at a time Some args fixed
Always unary Flexible

39. What is functional programming in JavaScript?

Answer:
A paradigm focused on:

  • Pure functions

  • Immutability

  • No side effects

  • Function composition


40. Explain pure vs impure functions

Answer:

Pure Impure
Same input → same output Depends on external state
No side effects Has side effects

41. What is memoization?

Answer:
Caching function results for performance.

const memo = {};
function fib(n) {
  if (memo[n]) return memo[n];
  memo[n] = n <= 1 ? n : fib(n-1) + fib(n-2);
  return memo[n];
}

42. Explain Symbol

Answer:
Symbol creates unique identifiers.

const id = Symbol("id");

Use case:

  • Avoid property name conflicts


43. What is the difference between for...in and for...of?

Answer:

for...in for...of
Iterates keys Iterates values
Objects Arrays/iterables

44. Explain destructuring

Answer:
Extract values from arrays or objects.

const { name, age } = user;

45. Explain spread vs rest operator

Answer:

// Spread
const arr2 = [...arr1];

// Rest
function sum(...args) {}

46. What is optional chaining?

Answer:
Safely access nested properties.

user?.profile?.name;

47. Explain nullish coalescing (??)

Answer:
Returns right-hand value only if left is null or undefined.

const name = userName ?? "Guest";

48. Explain Object.create()

Answer:
Creates object with specified prototype.

const obj = Object.create(proto);

49. How does JavaScript handle concurrency?

Answer:
Via:

  • Event loop

  • Callback queue

  • Microtask queue

  • Web APIs

JS is single-threaded but non-blocking.


50. Explain Web Storage security concerns

Answer:

  • Vulnerable to XSS

  • Not encrypted

  • Avoid sensitive data


51. Explain strict equality edge cases

Answer:

NaN === NaN // false
Object.is(NaN, NaN) // true

52. What is Object.is()?

Answer:
Better comparison for edge cases.


53. Explain ES6 modules vs CommonJS

Answer:

ES6 CommonJS
import/export require/module.exports
Static Dynamic
Browser & Node Node only

54. Explain lazy loading

Answer:
Loading resources when needed.

import("./module.js");

55. How do you prevent memory leaks in large applications?

Answer:

  • Cleanup event listeners

  • Use WeakMap

  • Clear timers

  • Avoid global variables


56. What is tree shaking?

Answer:
Removing unused code during build.


57. Explain JavaScript engine

Answer:
Components:

  • Parser

  • Interpreter

  • JIT compiler

  • Garbage collector

Example engines:

  • V8 (Chrome)

  • SpiderMonkey (Firefox)


58. Explain reflow and repaint

Answer:

Reflow Repaint
Layout recalculation Visual change
Expensive Less expensive

59. Explain requestAnimationFrame

Answer:
Optimized animation rendering.


60. How do you handle large data sets in JavaScript?

Answer:

  • Pagination

  • Virtualization

  • Web Workers

  • Chunking