Top Interview Questions
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.
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).
Answer:
Lightweight and fast
Interpreted (no compilation needed)
Object-based
Event-driven
Platform-independent
Supports functional programming
Answer:
| JavaScript | Java |
|---|---|
| Interpreted language | Compiled language |
| Used mainly for web | Used for applications |
| Loosely typed | Strongly typed |
| Runs in browser | Runs on JVM |
Answer:
Variables store data values. JavaScript has three ways to declare variables:
var x = 10;
let y = 20;
const z = 30;
var → old, function-scoped
let → block-scoped
const → block-scoped, value cannot be changed
Answer:
JavaScript has two types of data types.
Number
String
Boolean
Undefined
Null
Symbol
BigInt
Object
Array
Function
Example:
let name = "Alex"; // String
let age = 20; // Number
let isStudent = true; // Boolean
undefined and null?Answer:
undefined → variable declared but not assigned
null → intentional empty value
let a;
let b = null;
Answer:
Operators perform operations on values.
Arithmetic: + - * / %
Assignment: = += -=
Comparison: == === !=
Logical: && || !
== and ===?Answer:
== → compares values only
=== → compares value and type
5 == "5" // true
5 === "5" // false
Answer:
Functions are reusable blocks of code.
function add(a, b) {
return a + b;
}
Answer:
Arrow functions are a shorter syntax for functions.
const add = (a, b) => a + b;
Answer:
An array stores multiple values in a single variable.
let colors = ["red", "blue", "green"];
Answer:
Objects store data as key-value pairs.
let student = {
name: "John",
age: 21
};
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";
Answer:
An event is an action performed by the user.
Examples:
click
keypress
mouseover
button.onclick = function() {
alert("Clicked!");
};
this keyword?Answer:
this refers to the object that is currently calling the function.
Answer:
Hoisting moves variable and function declarations to the top of the scope.
console.log(x);
var x = 10; // no error
Answer:
Loops execute a block of code multiple times.
Types:
for
while
do-while
for (let i = 1; i <= 5; i++) {
console.log(i);
}
NaN?Answer:
NaN means Not a Number.
let result = "abc" / 10; // NaN
Answer:
Scope determines where variables can be accessed.
Types:
Global scope
Function scope
Block scope
Answer:
A callback function is passed as an argument to another function.
function greet(name, callback) {
callback();
}
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
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
null and undefined?Answer:
| null | undefined |
|---|---|
| Assigned value | Default value |
| Intentional empty | Not initialized |
| Type is object | Type is undefined |
Answer:
IIFE (Immediately Invoked Function Expression) runs as soon as it is defined.
(function () {
console.log("IIFE executed");
})();
setTimeout()?Answer:
Executes code after a specified delay.
setTimeout(() => {
console.log("Hello after 2 seconds");
}, 2000);
setInterval()?Answer:
Executes code repeatedly at a fixed time interval.
setInterval(() => {
console.log("Repeats every second");
}, 1000);
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");
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");
});
async and await?Answer:
Used to handle promises in a cleaner way.
async function fetchData() {
let result = await fetch(url);
console.log(result);
}
Answer:
The event loop handles asynchronous operations and executes them when the call stack is empty.
map()?Answer:
map() creates a new array by modifying each element.
let nums = [1, 2, 3];
let squares = nums.map(n => n * n);
filter()?Answer:
filter() returns elements that meet a condition.
let nums = [1, 2, 3, 4];
let even = nums.filter(n => n % 2 === 0);
reduce()?Answer:
reduce() reduces an array to a single value.
let sum = nums.reduce((total, n) => total + n, 0);
map() and forEach()?Answer:
| map | forEach |
|---|---|
| Returns new array | Returns nothing |
| Used for transformation | Used for iteration |
Answer:
JSON (JavaScript Object Notation) is used to store and transfer data.
Example:
{
"name": "John",
"age": 22
}
localStorage and sessionStorage?Answer:
| localStorage | sessionStorage |
|---|---|
| Permanent | Temporary |
| Data persists | Cleared when tab closes |
| Storage limit ~5MB | Storage limit ~5MB |
this in arrow functions?Answer:
Arrow functions do not have their own this.
They inherit this from the parent scope.
Answer:
Debouncing limits function execution until the user stops an action.
Example use case:
Search input
Window resize
Answer:
Throttling limits function execution to once per time interval.
Answer:
Handled using try...catch.
try {
let x = y + 1;
} catch (error) {
console.log(error);
}
Answer:
"use strict" enforces better coding practices.
"use strict";
x = 10; // error
Answer:
Automatic conversion of data types.
"5" + 2 // "52"
"5" - 2 // 3
Answer:
Shallow copy: Copies reference
Deep copy: Copies actual data
Example:
let copy = JSON.parse(JSON.stringify(obj));
Answer:
JavaScript uses prototypes for inheritance.
Answer:
Unused memory not released, often caused by:
Unremoved event listeners
Global variables
Answer:
An execution context is the environment in which JavaScript code is evaluated.
Global Execution Context
Function Execution Context
Eval Execution Context
Memory Creation Phase
Variables → undefined
Functions → stored fully
Execution Phase
Code executes line by line
π JavaScript is single-threaded and uses a 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
Answer:
Hoisting moves declarations to the top of scope.
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;
Answer:
TDZ is the time between variable creation and initialization where access is not allowed.
console.log(a); // TDZ
let a = 10;
Answer:
A closure allows a function to access variables from its parent scope even after execution.
Data hiding
Memoization
Counters
Event handlers
Example:
function createCounter() {
let count = 0;
return function () {
return ++count;
};
}
const counter = createCounter();
counter(); // 1
counter(); // 2
Answer:
The event loop manages async operations.
Call Stack
Web APIs
Microtask Queue (Promises)
Callback Queue (setTimeout)
π Microtasks have higher priority than callbacks
Order:
Call Stack → Microtasks → Callback Queue
setTimeout and PromisesAnswer:
| Feature | setTimeout | Promise |
|---|---|---|
| Queue | Callback | Microtask |
| Priority | Lower | Higher |
| Usage | Delays | Async logic |
this keywordAnswer:
this depends on how a function is called.
Global → window
Object method → object
Function → undefined (strict)
Arrow function → lexical this
Constructor → new object
const obj = {
name: "JS",
getName() {
return this.name;
}
};
Answer:
| Feature | Arrow | Normal |
|---|---|---|
| this | Lexical | Dynamic |
| arguments | β | β |
| constructor | β | β |
| hoisting | β | β |
Answer:
Copies references
const copy = {...obj};
Copies actual values
const deep = structuredClone(obj);
// or
JSON.parse(JSON.stringify(obj));
Answer:
JavaScript objects inherit properties via prototype chain.
function Person(name) {
this.name = name;
}
Person.prototype.sayHello = function () {
return "Hello " + this.name;
};
call, apply, and bindAnswer:
func.call(obj, a, b);
func.apply(obj, [a, b]);
const newFunc = func.bind(obj);
| Method | Execution |
|---|---|
| call | Immediate |
| apply | Immediate |
| bind | Later |
Answer:
Functions that:
Take functions as arguments
Return functions
Examples:
map, filter, reduce
map, filter, reduceAnswer:
arr.map(x => x * 2); // transform
arr.filter(x => x > 10); // condition
arr.reduce((a,b)=>a+b); // accumulate
Answer:
Transforming a function with multiple arguments into nested functions.
const add = a => b => c => a + b + c;
Answer:
Executes function after user stops action.
Use cases:
Search input
Resize events
Answer:
Executes function once per time interval.
Use cases:
Scroll events
Button clicks
Answer:
Promise states:
Pending
Fulfilled
Rejected
fetch(url)
.then(res => res.json())
.catch(err => console.error(err));
Answer:
Syntactic sugar over promises.
async function getData() {
try {
const res = await fetch(url);
} catch (e) {}
}
Answer:
try/catch
Promise .catch
Global error handler
Custom errors
Answer:
Occurs when memory is not released.
Global variables
Event listeners not removed
Closures holding references
Timers not cleared
Answer:
JavaScript automatically removes unused memory using mark-and-sweep algorithm.
Answer:
"use strict";
Benefits:
Prevents accidental globals
Throws more errors
Better performance
Answer:
ES6 modules
export default function(){}
import fn from "./file";
Benefits:
Encapsulation
Reusability
Tree shaking
Answer:
Debounce/throttle
Avoid deep DOM access
Use async loading
Minimize re-renders
Use Web Workers
Answer:
Data should not be modified directly.
const newArr = [...oldArr, 4];
Answer:
Handling events at parent instead of multiple children.
Benefits:
Better performance
Dynamic elements support
Answer:
Run JS in background threads without blocking UI.
Answer:
Security mechanism that controls cross-origin requests.
localStorage, sessionStorage, cookiesAnswer:
| Feature | localStorage | sessionStorage | cookies |
|---|---|---|---|
| Size | ~5MB | ~5MB | ~4KB |
| Expiry | Permanent | Tab close | Custom |
| Server | β | β | β |
Answer:
JavaScript uses automatic memory management.
Allocation – memory is allocated when variables are created
Usage – memory used during execution
Deallocation – garbage collector frees unused memory
Mark-and-Sweep
Reachable objects are marked
Unreachable objects are removed
Answer:
Weak references allow objects to be garbage-collected.
WeakMap
WeakSet
let wm = new WeakMap();
let obj = {};
wm.set(obj, "data");
obj = null; // eligible for GC
Use case:
Caching
Prevent memory leaks
Object.freeze() vs Object.seal()Answer:
| Method | Add | Delete | Modify |
|---|---|---|---|
| freeze | β | β | β |
| seal | β | β | β |
Object.freeze(obj);
Answer:
Event propagation has three phases:
Capturing
Target
Bubbling
element.addEventListener("click", handler, true); // capture
Answer:
Handling child events via parent element.
Benefits:
Less memory usage
Handles dynamic elements
Answer:
| Microtask | Macrotask |
|---|---|
| Promise | setTimeout |
| MutationObserver | setInterval |
| Higher priority | Lower priority |
Answer:
A stack overflow error occurs due to:
Infinite recursion
Excessive nested calls
Answer:
| Currying | Partial |
|---|---|
| One arg at a time | Some args fixed |
| Always unary | Flexible |
Answer:
A paradigm focused on:
Pure functions
Immutability
No side effects
Function composition
Answer:
| Pure | Impure |
|---|---|
| Same input → same output | Depends on external state |
| No side effects | Has side effects |
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];
}
SymbolAnswer:
Symbol creates unique identifiers.
const id = Symbol("id");
Use case:
Avoid property name conflicts
for...in and for...of?Answer:
| for...in | for...of |
|---|---|
| Iterates keys | Iterates values |
| Objects | Arrays/iterables |
Answer:
Extract values from arrays or objects.
const { name, age } = user;
Answer:
// Spread
const arr2 = [...arr1];
// Rest
function sum(...args) {}
Answer:
Safely access nested properties.
user?.profile?.name;
??)Answer:
Returns right-hand value only if left is null or undefined.
const name = userName ?? "Guest";
Object.create()Answer:
Creates object with specified prototype.
const obj = Object.create(proto);
Answer:
Via:
Event loop
Callback queue
Microtask queue
Web APIs
JS is single-threaded but non-blocking.
Answer:
Vulnerable to XSS
Not encrypted
Avoid sensitive data
Answer:
NaN === NaN // false
Object.is(NaN, NaN) // true
Object.is()?Answer:
Better comparison for edge cases.
Answer:
| ES6 | CommonJS |
|---|---|
| import/export | require/module.exports |
| Static | Dynamic |
| Browser & Node | Node only |
Answer:
Loading resources when needed.
import("./module.js");
Answer:
Cleanup event listeners
Use WeakMap
Clear timers
Avoid global variables
Answer:
Removing unused code during build.
Answer:
Components:
Parser
Interpreter
JIT compiler
Garbage collector
Example engines:
V8 (Chrome)
SpiderMonkey (Firefox)
Answer:
| Reflow | Repaint |
|---|---|
| Layout recalculation | Visual change |
| Expensive | Less expensive |
requestAnimationFrameAnswer:
Optimized animation rendering.
Answer:
Pagination
Virtualization
Web Workers
Chunking