JavaScript Fundamentals
1. What are the key features of JavaScript?
JavaScript is a high-level, interpreted programming language known for:
● Single-Threaded, Asynchronous Nature: It uses an event loop to handle non-blocking
operations, making it efficient for I/O tasks.
● Dynamic Typing: Variable types are determined at runtime, not compile time.
● Prototype-Based Inheritance: Objects inherit properties directly from other objects.
● First-Class Functions: Functions are treated like any other variable—they can be
passed as arguments, returned from other functions, and assigned to variables.
● Multi-Paradigm: It supports event-driven, functional, and imperative programming
styles.
2. What is the difference between var, let, and const?
The key differences lie in their scope, hoisting, and re-assignability.
Feature var let const
Scope Function-scoped Block-scoped ({}) Block-scoped ({})
Hoisting Hoisted and Hoisted but not Hoisted but not
initialized with initialized initialized
undefined. (Temporal Dead (Temporal Dead
Zone). Zone).
Re-assignment Can be re-declared Can be re-assigned Cannot be
and re-assigned. but not re-declared re-assigned or
in the same scope. re-declared.
Global Object Creates a property Does not create a Does not create a
on the global property on the property on the
object (window) if global object. global object.
declared globally.
3. What is hoisting in JavaScript?
Hoisting is JavaScript's default behavior of moving declarations to the top of their containing
scope during the compilation phase.
● var declarations are hoisted and initialized with a value of undefined. You can access
them before the line they were declared without an error, but you'll get undefined.
● let and const declarations are also hoisted, but they are not initialized. Accessing them
before the declaration results in a ReferenceError. This period is known as the Temporal
Dead Zone (TDZ).
● Function declarations are fully hoisted, meaning you can call a function before it's
defined in the code.
4. What are closures in JavaScript?
A closure is a feature where an inner function has access to the outer (enclosing) function's
variables and scope, even after the outer function has finished executing. Closures are
created every time a function is created.
Example:
JavaScript
function createCounter() {
let count = 0; // This variable is "closed over"
return function() {
count++;
[Link](count);
};
}
const counter = createCounter(); // counter is a function that has access to the 'count' variable.
counter(); // 1
counter(); // 2
5. What is the difference between == and ===?
● == (Loose Equality): Compares two values for equality after performing type conversion
if necessary. This can lead to unexpected results (e.g., "1" == 1 is true).
● === (Strict Equality): Compares two values for equality without performing type
conversion. If the types are different, it returns false. This is the recommended
comparison operator.
6. What is the difference between null and undefined?
● undefined means a variable has been declared but has not yet been assigned a value.
It's the default value.
● null is an assignment value. It can be assigned to a variable as a representation of "no
value" or an intentional absence of any object value.
Asynchronous JavaScript
7. What are arrow functions, and how are they different from regular
functions?
Arrow functions are a more concise syntax for writing function expressions, introduced in
ES6.
Key Differences:
1. Syntax: Arrow functions offer a shorter syntax.
JavaScript
// Regular function
function add(a, b) { return a + b; }
// Arrow function
const addArrow = (a, b) => a + b;
2. this Binding: Arrow functions do not have their own this context. They inherit this from
their parent scope (lexical this). Regular functions get their own this value depending on
how they are called.
3. arguments Object: Arrow functions do not have their own arguments object. You can
use rest parameters (...args) instead.
4. Constructor: Arrow functions cannot be used as constructors and will throw an error
when used with new.
8. What is the scope of a variable in JavaScript?
Scope determines the accessibility of variables and functions at various parts of your code.
● Global Scope: Variables declared outside any function are in the global scope and are
accessible from anywhere.
● Function Scope: Variables declared with var inside a function are accessible only within
that function.
● Block Scope: Variables declared with let and const inside a block (e.g., inside an if
statement or a for loop, denoted by {}) are accessible only within that block.
9. What is the event loop in JavaScript?
The event loop is the mechanism that allows [Link] and browsers to perform non-blocking
asynchronous operations, despite JavaScript being single-threaded. It continuously checks if
the call stack is empty and, if so, pushes tasks from the queues to the stack for execution.
● Call Stack: A data structure that records where we are in the program. When a function
is called, it's pushed onto the stack. When it returns, it's popped off.
● Callback Queue (or Task Queue): When an async operation (like setTimeout or a DOM
event) completes, its callback function is placed in the Callback Queue.
● Microtask Queue (or Job Queue): Callbacks from Promises (.then(), .catch(), .finally())
and queueMicrotask are placed here. Microtasks have higher priority and are executed
before the next task from the Callback Queue.
The loop's order is:
1. Execute tasks in the Call Stack until it's empty.
2. Execute all tasks in the Microtask Queue.
3. Execute one task from the Callback Queue.
4. Repeat.1
10. What are Promises? How are they different from callbacks?2
A Promise is an object representing the eventual completion (or failure) of an asynchronous
operation. It exists in one of three states:3
● pending: The i4nitial state, neither fulfilled nor rejected.
● fulfilled: The operation completed successfully.
● rejected: The operation failed.
Promises vs. Callbacks:
● Readability: Promises allow for cleaner, more readable code by avoiding "callback hell"
(deeply nested callbacks). You can chain .then() methods.
● Error Handling: Promises have a built-in .catch() method for centralized error handling,
whereas callbacks require error handling for each individual callback function.
● Control: Promises give the caller more control over when and how to handle the result,
whereas callbacks are executed immediately upon completion.
11. What is async/await in JavaScript?
async/await is syntactic sugar built on top of Promises, making asynchronous code look and
behave more like synchronous code.
● async function: A function declared with the async keyword implicitly returns a Promise.
● await operator: The await keyword is used inside an async function to pause its
execution and wait for a Promise to resolve. It "unwraps" the value from the Promise.
Improvement: It dramatically improves the readability and maintainability of asynchronous
code by eliminating the need for .then() chains.
JavaScript
// Using .then()
function fetchData() {
fetch('[Link]
.then(response => [Link]())
.then(data => [Link](data))
.catch(error => [Link](error));
}
// Using async/await
async function fetchDataAsync() {
try {
const response = await fetch('[Link]
const data = await [Link]();
[Link](data);
} catch (error) {
[Link](error);
}
}
12. What is the difference between synchronous and asynchronous
code?
● Synchronous (or "sync") code is blocking. It executes line by line, and each statement
must complete before the next one begins. If a function takes a long time to run, it will
block the entire program.
● Asynchronous (or "async") code is non-blocking. It allows the program to continue
running while waiting for a long-running task (like a network request or file read) to
complete. The result is handled later, typically with a callback, Promise, or async/await.
DOM and Browser APIs
13. What is the DOM? How is it manipulated using JavaScript?
The DOM (Document Object Model) is a programming interface for web documents. It
represents the page's structure as a tree of objects, where each object corresponds to a part
of the document (e.g., an element, attribute, or text).
JavaScript manipulates the DOM by:
● Selecting elements: Using methods like [Link](),
[Link](), and [Link]().
● Changing content: Using properties like .innerHTML, .textContent.
● Changing styles: Modifying the .style property of an element.
● Adding/Removing elements: Using methods like [Link](),
[Link](), and [Link]().
● Handling events: Using [Link]() to respond to user interactions.
14. What is event delegation in JavaScript?
Event delegation is a technique where you add a single event listener to a parent element to
manage events for all of its child elements. When an event is triggered on a child, it "bubbles
up" to the parent. The listener on the parent can then check the [Link] property to
determine which child element originated the event.
Benefits:
● Performance: Reduces the number of event listeners, saving memory.
● Dynamic Elements: Works automatically for child elements that are added to the DOM
after the listener has been attached.
15. What are higher-order functions? Give examples.
A higher-order function is a function that either:
1. Takes one or more functions as arguments.
2. Returns a function as its result.
Examples:
● [Link](): Takes a function as an argument and applies it to every element
in an array.
● [Link](): Takes a predicate function and returns a new array with only
the elements that pass the test.
● setTimeout(): Takes a callback function to execute after a delay.
● A function that returns another function (like the closure example in question 4).
16. What are pure functions and side effects in JavaScript?
● A pure function is a function that, given the same input, will always return the same
output and has no observable side effects. It depends only on its input arguments.
● A side effect is any interaction a function has with the outside world beyond returning a
value. Examples include modifying a global variable, writing to the console ([Link]),
making an HTTP request, or changing the DOM.
Pure functions are predictable, testable, and easier to reason about, which is a core principle
of functional programming.
17. What is the difference between map(), filter(), and reduce()?
These are three common array methods that are higher-order functions. They all iterate over
an array and return a new value without modifying the original array.
● map(): Transforms each element of an array and returns a new array of the same length
with the transformed elements.
JavaScript
const numbers = [1, 2, 3];
const doubled = [Link](n => n * 2); // [2, 4, 6]
● filter(): Selects elements from an array that meet a certain condition and returns a new
array containing only the elements that pass the test.
JavaScript
const numbers = [1, 2, 3, 4, 5];
const evens = [Link](n => n % 2 === 0); // [2, 4]
● reduce(): Aggregates all elements of an array into a single value (e.g., a number, string,
or object). It takes a reducer function and an optional initial value.
JavaScript
const numbers = [1, 2, 3, 4, 5];
const sum = [Link]((accumulator, currentValue) => accumulator + currentValue, 0);
// 15
18. What are JavaScript data types? Explain primitive vs reference
types.
JavaScript has eight data types.
Primitive Types: Data is stored directly in the location the variable accesses. They are
immutable.
1. String
2. Number
3. BigInt
4. Boolean
5. undefined
6. Symbol
7. null
Reference Types: The variable stores a reference (or pointer) to the object's location in
memory, not the object itself. They are mutable.
8. Object (This includes arrays, functions, and other objects).
When you copy a primitive value, you get a new, separate value. When you copy a reference
value, you get a new reference pointing to the same underlying object.
19. What is the difference between shallow copy and deep copy?
● Shallow Copy: Creates a new object or array, but for any nested objects or arrays, it only
copies the reference to them. Modifying a nested object in the copy will also modify the
original. Methods like [Link]() and the spread syntax (...) create shallow copies.
● Deep Copy: Creates a new object or array and recursively copies all nested objects and
arrays, creating new, independent copies of them as well. Modifying a nested object in
the copy will not affect the original. A common way to create a deep copy is using
[Link]([Link](object)), but this has limitations (it can't copy functions,
undefined, or Symbols).
20. What is the difference between call(), apply(), and bind()?
These methods are used to set the this value for a function, regardless of how it's called.
● call(thisArg, arg1, arg2, ...): Invokes the function immediately and allows you to pass
arguments one by one.
● apply(thisArg, [arg1, arg2, ...]): Invokes the function immediately but requires you to
pass arguments as an array.
● bind(thisArg, arg1, arg2, ...): Does not invoke the function immediately. It returns a
new function with the this value permanently bound to thisArg. You can call this new
function later.
21. What are IIFEs (Immediately Invoked Function Expressions)?
An IIFE is a JavaScript function that is executed as soon as it is defined. It's created by
wrapping a function expression in parentheses, which tells the parser to treat it as an
expression, and then immediately calling it with another set of parentheses.
Purpose: The primary use case is to create a private scope to avoid polluting the global
namespace. Variables declared inside an IIFE are not accessible from the outside.
JavaScript
(function() {
const privateVar = "I am private";
[Link](privateVar);
})(); // "I am private"
// [Link](privateVar); // Uncaught ReferenceError: privateVar is not defined
Prototypes and this
22. What is a prototype? What is prototypal inheritance?
In JavaScript, every object has a hidden internal property called [[Prototype]] which is a
reference to another object or null. This other object is its prototype.
Prototypal Inheritance is the mechanism by which objects inherit properties and methods
from their prototype. When you try to access a property on an object, if the property isn't
found on the object itself, the JavaScript engine looks for it on the object's prototype. If it's
not found there, it looks at the prototype's prototype, and so on, up the prototype chain until
it either finds the property or reaches the end of the chain (null).
23. What is the difference between class and prototype-based
inheritance?
● Prototype-Based Inheritance: The core model in JavaScript. Objects inherit directly
from other objects. It's more flexible and dynamic.
● Class-Based Inheritance: Introduced in ES6, class syntax is primarily syntactic sugar
over JavaScript's existing prototype-based inheritance. It provides a more familiar and
structured syntax for developers coming from class-based languages like Java or C++.
Under the hood, it still uses prototypes.
The class syntax simplifies creating constructor functions and managing the prototype chain.
24. What is the use of the "this" keyword in JavaScript?
The this keyword refers to the context in which a function is executed. Its value is determined
by how a function is called, not where it is defined.
● Global Context: In the global scope, this refers to the global object (window in browsers,
global in [Link]).
● Method Call: When a function is called as a method of an object ([Link]()),
this refers to the object itself.
● Function Call: In a simple function call (myFunction()), this refers to the global object in
non-strict mode, and undefined in strict mode.
● Constructor Call: When a function is used as a constructor with the new keyword, this
refers to the newly created instance.
● call(), apply(), bind(): These methods allow you to explicitly set the this value.
25. How does "this" behave in arrow functions vs regular functions?
This is a critical distinction:
● Regular Functions: Get their own this value based on how they are called (the execution
context).
● Arrow Functions: Do not have their own this. They inherit this from their parent scope at
the time they are defined (lexical scoping). This behavior is fixed and cannot be changed
by bind(), call(), or apply().
This makes arrow functions particularly useful for callbacks inside methods where you want to
preserve the this context of the method.
Advanced Topics
26. What are modules in JavaScript? Difference between CommonJS
and ES6 modules?
Modules allow you to break up your code into separate, reusable files. This improves
organization, maintainability, and helps manage dependencies.
Feature CommonJS (CJS) ES6 Modules (ESM)
Usage Primarily used in [Link]. The standard for modern
JavaScript, used in
browsers and [Link].
Syntax require() to import, import to import, export to
[Link] to export. export.
Loading Synchronous: Modules are Asynchronous: Modules
loaded at the point require are parsed and loaded
is called. before execution.
Tree-shaking Not easily tree-shakeable. Designed to be statically
analyzable, which allows
for effective tree-shaking
(removing unused code).
27. What is the difference between localStorage, sessionStorage, and
cookies?
This table summarizes the main differences in web browser storage:
Feature cookies sessionStorage localStorage
Storage Limit ~4KB ~5-10MB ~5-10MB
Expiration Manually set Expires when the Persists until
expiration date. tab is closed. manually cleared.
Scope Sent with every Accessible only Accessible from
HTTP request to within the same any tab/window
the server. tab/window. within the same
origin.
Accessibility Accessible on both Client-side only. Client-side only.
server-side and
client-side.
28. What is a debounce function? What is throttling?
Debounce and throttle are two techniques to control how often a function is executed,
commonly used for performance optimization.
● Debounce: Groups a burst of events into a single one. It executes the function only after
a certain amount of time has passed without that event being fired again.
○ Use Case: A search bar's autocomplete. You wait until the user stops typing to send
the API request.
● Throttle: Ensures that a function is executed at most once per specified time interval,
regardless of how many times the event is fired.
○ Use Case: Handling scroll or resize events. You might want to run a calculation at
most every 200ms, not on every single pixel scrolled.
29. What is the difference between setTimeout() and setInterval()?
● setTimeout(callback, delay): Executes the callback function once after the specified
delay in milliseconds.
● setInterval(callback, delay): Executes the callback function repeatedly at every specified
delay interval. It continues until it is cleared with clearInterval().
30. What are memory leaks? How can you prevent them?
A memory leak occurs when a program allocates memory but fails to release it when it's no
longer needed. Over time, this can consume all available memory and crash the application.
Common Causes in JavaScript:
1. Accidental Global Variables: Variables created without let, const, or var can become
properties of the global object and never get garbage collected.
2. Forgotten Timers or Callbacks: setInterval timers or event listeners that are never
cleared can keep references to objects in memory.
3. Closures: Closures that hold references to large objects can prevent those objects from
being garbage collected.
4. Detached DOM Elements: Storing a reference to a DOM element in JavaScript after it
has been removed from the DOM.
Prevention:
● Always use let or const to declare variables to avoid accidental globals. Use strict mode
('use strict').
● Always clear intervals (clearInterval) and remove event listeners (removeEventListener)
when they are no longer needed, especially in single-page applications when
components unmount.
● Be mindful of what variables are captured in closures.
● Avoid storing references to DOM elements that might be removed.
31. What are the different ways to handle errors in JavaScript?
1. try...catch...finally block: The standard way to handle synchronous errors.
○ try: Code that might throw an error.
○ catch: Code to run if an error occurs.
○ finally: Code that runs regardless of whether an error was thrown.
2. Promise .catch() method: The standard way to handle asynchronous errors in Promises.
3. async/await with try...catch: You can wrap await calls in a try...catch block to handle
rejected Promises.
4. Error-first callbacks: A convention (common in [Link]) where the first argument to a
callback function is an error object. If there's no error, it's null.
5. [Link] and [Link]: Global error handlers for
catching uncaught synchronous errors and unhandled promise rejections, respectively.
Useful for logging and reporting.
32. What is the difference between frontend and backend JavaScript?
The core language is the same, but the environment and APIs are different.
● Frontend JavaScript (in the Browser):
○ Environment: Runs in a web browser.
○ Purpose: To create interactive user interfaces and manipulate the DOM.
○ APIs: Has access to Browser APIs like the DOM, Fetch API, localStorage,
sessionStorage, and window object.
○ Security: Runs in a sandboxed environment with security restrictions (e.g., CORS).
● Backend JavaScript (e.g., [Link]):
○ Environment: Runs on a server.
○ Purpose: To build server-side applications, APIs, and interact with databases.
○ APIs: Has access to server-side APIs for file system access (fs module),
networking (http module), database connections, and operating system
interactions. It has no access to the DOM.
○ Security: Has full access to the machine it's running on, so security is managed
differently (e.g., authentication, authorization).
33. What is CORS and how does JavaScript handle it?
CORS (Cross-Origin Resource Sharing) is a browser security mechanism that restricts a
web page from making requests to a different domain (origin) than the one that served the
page. An origin is a combination of protocol, domain, and port.
How it's handled:
● It's a server-side configuration, not a client-side one. The server must include specific
HTTP headers in its response to tell the browser that it's okay for the web page from
another origin to access its resources.
● The primary header is Access-Control-Allow-Origin. For example,
Access-Control-Allow-Origin: * allows any origin, while Access-Control-Allow-Origin:
[Link] allows only that specific origin.
● For requests that can modify data (like POST, PUT, DELETE), the browser first sends a
"preflight" request using the OPTIONS method to check for permission. The server must
respond correctly to this preflight request for the actual request to be sent.
JavaScript itself doesn't "handle" CORS; the browser enforces it based on the headers sent
by the server.
34. What are web APIs and how are they used in JavaScript?
Web APIs (or Browser APIs) are built-in functionalities provided by the web browser that are
not part of the core JavaScript language itself. They allow JavaScript to interact with the
browser and the user's computer.
Examples:
● DOM API: For manipulating the HTML and CSS of a page.
● Fetch API / XMLHttpRequest: For making HTTP requests to servers.
● Console API: For logging information to the developer console ([Link]).
● Storage API: localStorage and sessionStorage.
● Geolocation API: For getting the user's location.
● Timers: setTimeout and setInterval.
JavaScript uses these APIs by calling their methods and accessing their properties, which are
typically available on the global window object.
35. What are the new features introduced in ES6 and beyond
(ES7-ES13)?
Here's a brief overview of some major features:
● ES6 (2015): The biggest update.
○ let and const
○ Arrow Functions
○ Promises
○ Classes
○ Template Literals
○ Destructuring Assignment
○ Default, Rest, and Spread parameters
○ Modules (import/export)
● ES7 (2016):
○ [Link]()
○ Exponentiation Operator (**)
● ES8 (2017):
○ async/await
○ [Link](), [Link]()
○ String padding (padStart, padEnd)
● ES9 (2018):
○ Rest/Spread Properties for objects (...)
○ Asynchronous Iteration (for-await-of)
○ [Link]()
● ES10 (2019):
○ [Link](), [Link]()
○ [Link]()
○ [Link](), [Link]()
● ES11 (2020):
○ Nullish Coalescing Operator (??)
○ Optional Chaining (?.)
○ [Link]()
○ globalThis
○ Dynamic import()
● ES12 (2021):
○ [Link]()
○ [Link]()
○ Logical Assignment Operators (&&=, ||=, ??=)
● ES13 (2022):
○ Top-level await (can use await outside of async functions in modules)
○ .at() method for arrays and strings (allows negative indexing)
○ [Link]()
Sources
1. [Link]