JavaScript is a high-level, interpreted, dynamic programming language primarily used to make web pages interactive.
It is one of the core technologies of the web, alongside:
-
HTML → Structure
-
CSS → Styling
-
JavaScript → Behavior / Interactivity
JavaScript runs inside the browser using engines like V8 (Chrome) and can also run outside the browser using Node.js.
Why is JavaScript Needed?
Without JavaScript, websites would be static.
JavaScript allows:
-
Dynamic content updates
-
Form validation
-
Interactive UI elements
-
API calls without reloading the page
-
Real-time updates
Example:
-
Button click actions
-
Showing/hiding elements
-
Updating data without refreshing the page
Key Features of JavaScript
-
Interpreted Language
-
Runs line by line (no separate compilation required).
-
-
Dynamically Typed
-
Variable types are decided at runtime
-
-
Prototype-Based
-
Uses prototypes instead of classical inheritance.
-
-
First-Class Functions
-
Functions can be stored in variables, passed as arguments, returned from other functions.
-
-
Event-Driven
-
Executes code based on events (click, submit, hover).
-
-
Asynchronous & Non-Blocking
-
Uses callbacks, Promises, async/await.
-
Handles tasks like API calls efficiently.
-
-
Cross-Platform
-
Works in browsers, servers, mobile apps, desktop apps.
-
JavaScript was created by Brendan Eich in 1995.
He developed it while working at Netscape Communications Corporation.
Important Fact:
-
Initially named Mocha
-
Later renamed to LiveScript
-
Finally renamed to JavaScript (for marketing reasons to associate with Java, which was popular at that time).
Main Purpose:
To add interactivity to websites.
At that time (1995), websites were completely static — built only with HTML.
Users could not:
-
Validate forms instantly
-
Respond to button clicks dynamically
-
Update content without reloading
Netscape wanted a scripting language that:
-
Runs directly in the browser
-
Is easy for developers to learn
-
Makes web pages interactive
So Brendan Eich built JavaScript.
What Problem Did It Solve?
Before JavaScript:
-
Every user action required server communication
-
Page reload was required for validation
-
User experience was slow
After JavaScript:
-
Client-side validation
-
Faster UI updates
-
Dynamic content without reload
-
Better user experience
Yes, JavaScript is a case-sensitive language.
This means:
-
Variable names
-
Function names
-
Keywords
-
Object properties
are treated differently based on uppercase and lowercase letters.
Traditional Understanding
Originally, JavaScript was considered an interpreted language because:
-
It runs line by line
-
No separate compilation step like C or C++
-
Code runs directly inside the browser
What Happens in Modern JavaScript Engines?
Modern engines like:
-
Chrome → V8
-
Firefox → SpiderMonkey
-
Edge → Chakra
use Just-In-Time (JIT) compilation.
How It Works:
-
JavaScript code is parsed.
-
Converted into bytecode.
-
Frequently used code is compiled into machine code.
-
Optimizations are applied at runtime.
Why Is JIT Used?
To improve performance.
Without JIT:
-
Slower execution
-
Less optimization
With JIT:
-
Faster performance
-
Dynamic optimization
-
Better memory usage
ECMAScript is the standard specification on which JavaScript is based.
It defines:
-
Syntax
-
Rules
-
Features
-
Core functionalities
JavaScript is an implementation of the ECMAScript standard.
Why is ECMAScript Needed?
Before standardization:
-
Different browsers implemented JavaScript differently.
-
Code worked in one browser but failed in another.
To solve this inconsistency:
-
In 1997, JavaScript was standardized by ECMA International.
-
The standard was named ECMAScript.
This ensured:
-
Cross-browser compatibility
-
Consistent behavior
-
Structured evolution of the language
ES6 (ECMAScript 2015) is the 6th version of the ECMAScript standard, which defines how JavaScript should work.
It was released in 2015 and introduced major improvements to the language.
Why ES6 Is Important
ES6 modernized JavaScript by:
-
Making code cleaner and shorter
-
Improving readability
-
Introducing better scoping
-
Supporting modular programming
-
Enabling modern frameworks like React, Angular, and Vue
It is considered one of the biggest updates in JavaScript history.
Major Features Introduced in ES6
-
let and const (block scope)
-
Arrow functions
-
Template literals
-
Destructuring
-
Default parameters
-
Rest and spread operators
-
Classes
-
Modules (import/export)
-
Promises
Data types in JavaScript define the type of value a variable can hold.
Since JavaScript is a dynamically typed language, you don’t need to declare the type explicitly. The type is determined at runtime
Types of Data in JavaScript
JavaScript has two main categories:
-
Primitive Data Types
-
Non-Primitive (Reference) Data Types
Types of Primitive Data
-
Number
-
String
-
Boolean
-
Undefined
-
Null
-
BigInt
-
Symbol
Primitive Data Types
Primitive data types are basic data types that store a single value directly in memory.
They are:
-
Immutable (cannot be changed)
-
Stored by value
Types of Primitive Data
JavaScript has 7 primitive types:
-
Number
-
String
-
Boolean
-
Undefined
-
Null
-
BigInt
-
Symbol
Non-Primitive Data Types (Reference Types)
Definition
Non-primitive data types are complex data types that store collections of values.
They are:
-
Mutable
-
Stored by reference
Examples
-
Object
-
Array
-
Function
-
Date
-
Map
-
Set
A variable is a container used to store data values in a program.
It allows us to:
-
Store information
-
Reuse values
-
Update data during execution
Why Are Variables Needed?
Without variables:
-
We cannot store user input
-
Cannot perform calculations
-
Cannot manipulate data
-
Cannot build dynamic applications
Variables are fundamental to programming.
How to Declare a Variable in JavaScript?
In JavaScript, we declare variables using:
-
var -
let -
const
Features of var
-
Function-scoped
-
Can be redeclared
-
Can be updated
-
Hoisted (initialized as
undefined)
Features of let
-
Block-scoped
-
Cannot be redeclared in same scope
-
Can be updated
-
Hoisted but not initialized (Temporal Dead Zone)
Features of const
-
Block-scoped
-
Cannot be redeclared
-
Cannot be reassigned
-
Must be initialized during declaration
| Feature | var | let | const |
|---|---|---|---|
| Scope | Function | Block | Block |
| Redeclare | Yes | No | No |
| Reassign | Yes | Yes | No |
| Hoisted | Yes | Yes | Yes |
| TDZ | No | Yes | Yes |
11. What is scope in JavaScript ?
Why Scope is Important?
-
Prevents variable conflicts
-
Protects data
-
Helps in memory management
-
Avoids accidental overwriting
Scope is one of the most important core concepts in JavaScript interviews.
Types of Scope in JavaScript
JavaScript has mainly:
-
Global Scope - A variable declared outside any function or block.
-
Function Scope - Variables declared using
varinside a function are accessible only inside that function. -
Block Scope - Variables declared using
letandconstinside{}are accessible only inside that block -
Lexical Scope - Inner functions can access variables from their outer functions.
why Hoisting Exists?
Before executing the code, JavaScript:
-
Scans the code
-
Allocates memory for variables and functions
-
Then executes line by line
This pre-processing phase causes hoisting.
| Type | Hoisted? | Initialized? |
|---|---|---|
| var | Yes | Yes (undefined) |
| let | Yes | No (TDZ) |
| const | Yes | No (TDZ) |
| Function Declaration | Yes | Yes |
| Function Expression | Partially | No |
The Temporal Dead Zone (TDZ) is the time period between:
-
When a variable is hoisted
-
And when it is initialized
During this period, accessing the variable results in a ReferenceError.
TDZ applies to:
-
let -
const
Why Does TDZ Exist?
TDZ was introduced in ES6 to:
-
Prevent accidental access before initialization
-
Avoid bugs caused by
varhoisting -
Encourage better coding practices
14. What is undefined ?
undefined is a primitive data type in JavaScript that represents A variable that has been declared but has not been assigned a value.15. What is null ?
null is a primitive value in JavaScript that represents An intentional absence of any object value.Why Do We Use null?
We use null when:
-
We want to reset a variable
-
We want to indicate “empty value”
-
We expect a value later
-
We intentionally clear data
| Feature | undefined | null | undeclared |
|---|---|---|---|
| Declared? | Yes | Yes | No |
| Assigned? | No | Yes | No |
| Who assigns? | JavaScript | Developer | Nobody |
| Type | "undefined" | "object" | Error |
| Accessing it | Gives undefined | Gives null | ReferenceError |
17. What are truthy and falsy values ?
In JavaScript, truthy and falsy values determine how values behave in a boolean context (like inside if conditions).
When JavaScript evaluates a condition, it implicitly converts values to true or false.
Falsy Values
Falsy values are values that convert to false in a boolean context.
false
0
-0
0n // BigInt zero
"" // Empty string
null
undefined
NaN
Truthy Values
Any value that is not falsy is truthy.
true
1
-1
"hello"
"0"
[]
{}
function() {}
NaN stands for Not A Number When Does NaN Occur?
NaN occurs when:
1. Performing Invalid Mathematical Operations
2. Converting Non-Numeric Strings to Number
3. Invalid Math Operations
typeof is a unary operator in JavaScript used to determine the data type of a variable or value.
It returns a string indicating the type.
Basic Syntax
Why typeof is Important?
-
Type checking
-
Debugging
-
Conditional logic
-
Validation
Common Return Values
| Value | typeof Result |
|---|---|
| Number | "number" |
| String | "string" |
| Boolean | "boolean" |
| Undefined | "undefined" |
| Null | "object" |
| Object | "object" |
| Array | "object" |
| Function | "function" |
| Symbol | "symbol" |
| BigInt | "bigint" |
Type coercion is the automatic or explicit conversion of one data type into another in JavaScript.
JavaScript is a dynamically typed language, so it automatically converts types when needed.
Types of Type Coercion
There are two types:
-
Implicit Coercion (Automatic)
-
Explicit Coercion (Manual Conversion)
Implicit Type Coercion
JavaScript automatically converts data types during operations.
Example 1: String + Number
+operator converts number to string.-
String concatenation happens.
Example 2: String - Number
-forces numeric conversion.-
"5" becomes number 5.
Explicit Type Coercion
Manually converting types using functions.
Convert to Number
Convert to String
21. Implicit vs explicit type conversion ?
Type conversion (Type Coercion) means converting a value from one data type to another.
There are two types:
-
Implicit Type Conversion (Automatic)
-
Explicit Type Conversion (Manual)
Implicit Type Conversion (Automatic)
Definition
Implicit conversion happens automatically when JavaScript converts data types during operations.
Example 1: String + Number
+operator converts number to string.-
String concatenation happens.
Example 2: String - Number
-operator forces numeric conversion.-
"5" becomes number 5.
Example 3: Loose Equality (==)
"5" is converted to number 5.
Characteristics of Implicit Conversion
Happens automatically
Can cause unexpected bugs
Common with ==, +, -, *, /
Based on internal JavaScript rules
Explicit Type Conversion (Manual)
Definition
Explicit conversion is when the developer manually converts one data type to another using built-in functions.
Convert to Number
Convert to String
Convert to Boolean
Characteristics of Explicit Conversion
Done intentionally
More predictable
Reduces bugs
Preferred in production code
Comparison Table (Important for Interview)
| Feature | Implicit | Explicit |
|---|---|---|
| Done By | JavaScript | Developer |
| Control | No | Yes |
| Risk | Higher (unexpected behavior) | Lower |
| Example | "5" + 2 | Number("5") |
22. Difference between == and === ?
Definition
-
==→ Loose equality operator -
===→ Strict equality operator
The main difference is type coercion.
== (Loose Equality)
-
Compares values after performing implicit type conversion
-
If data types are different, JavaScript converts one type to another before comparison
-
Can produce unexpected results
=== (Strict Equality)
-
Compares both value and data type
-
Does NOT perform type coercion
-
Safer and more predictable
The conditional (ternary) operator is a shorthand way of writing an if...else statement.
It is called “ternary” because it takes three operands.
Syntax
How It Works
-
If the condition is true → first expression executes
-
If the condition is false → second expression executes
When to Use It
-
Simple conditions
-
Assigning values based on condition
-
Short, readable expressions
break and continue are used inside loops (and switch) to control flow.1. break Statement
Definition
The break statement is used to exit a loop or switch statement immediately.
When break executes:
-
The loop stops completely
-
Control moves to the next statement after the loop
Example (Loop)
Output:
1
2
The loop stops when i === 3.
2. continue Statement
Definition
The continue statement is used to skip the current iteration of a loop and move to the next iteration.
It does NOT stop the loop entirely.
Example
Output:
1
2
4
5
When i === 3, that iteration is skipped.
Key Difference
-
break→ Stops the loop completely -
continue→ Skips current iteration, continues loop
A function in JavaScript is a reusable block of code designed to perform a specific task.
Functions help in:
-
Organizing code
-
Avoiding repetition
-
Improving readability
-
Making code modular
Why Functions Are Needed
-
To execute code multiple times
-
To break complex logic into smaller parts
-
To improve maintainability
-
To follow DRY principle (Don’t Repeat Yourself)
Basic Syntax
Types of Functions in JavaScript
- Function Declaration
-
Function Expression
-
Arrow Function
-
Anonymous Function
-
Immediately Invoked Function Expression (IIFE)
Function Declaration
A function declaration defines a named function using the function keyword.
Syntax
Characteristics
-
Has a function name
-
Fully hoisted (both declaration and definition)
-
Can be called before it appears in code
Example (Hoisting)
Function Expression
A function expression is when a function is assigned to a variable.
Syntax
Characteristics
-
Can be named or anonymous
-
Not fully hoisted
-
Cannot be called before definition
-
Treated like a variable
Example (No Hoisting)
Only the variable is hoisted (if var), not the function body.
An anonymous function is a function without a name.
It is usually used:
-
As a function expression
-
As a callback
-
Inside other functions
-
In IIFE (Immediately Invoked Function Expressions)
Why Anonymous Functions Are Used
-
When the function does not need to be reused
-
When passing functions as arguments (callbacks)
-
To avoid polluting the global scope
-
In functional programming patterns
Arrow functions are a shorter syntax for writing functions, introduced in ES6 (2015).
They use the => (arrow) syntax.
Basic Syntax
Key Features
-
Shorter and cleaner syntax
-
Do NOT have their own
this -
Do NOT have their own
argumentsobject -
Cannot be used as constructors
-
Not hoisted like function declarations
When to Use Arrow Functions
-
Short functions
-
Callbacks
-
Functional programming
-
When you need lexical
this
Avoid when:
-
You need your own
this -
You need a constructor
A first-class function means:
Functions in JavaScript are treated like any other value.
This means functions can:
-
Be assigned to variables
-
Be passed as arguments to other functions
-
Be returned from other functions
-
Be stored inside objects or arrays
JavaScript is called a first-class function language because it supports all of these.
Why This Is Important
First-class functions enable:
-
Callbacks
-
Higher-order functions
-
Closures
-
Functional programming patterns
A unary function is a function that takes exactly one argument (one parameter).
“Unary” means “one”.
Syntax Example
Why Unary Functions Are Important
Unary functions are common in:
-
Functional programming
-
Array methods like
map,filter -
Mathematical operations
-
Higher-order functions
The arguments object is a special array-like object available inside regular (non-arrow) functions.
It contains all the arguments passed to the function, regardless of the number of parameters defined.
Characteristics
-
Available only inside regular functions
-
Not available in arrow functions
-
Array-like (has length and index), but not a real array
-
Does not support array methods directly (like map, filter)
undefined) is passed.Syntax
Important Behavior
Default value is used only when:
-
Argument is not passed
-
Argument is explicitly
undefined
Why Default Parameters Are Useful
Prevents
undefinederrors-
Makes functions safer
-
Reduces need for manual checks
-
Cleaner than old method
Template literals are a way to create strings using backticks ( ) instead of single or double quotes.
They were introduced in ES6 and allow:
-
String interpolation
-
Multi-line strings
-
Embedded expressions
Syntax
Why Template Literals Are Important
-
Cleaner and more readable
-
Avoid messy string concatenation
-
Useful in dynamic UI rendering
-
Common in React and Node.js
) without needing special characters like \n.Syntax
Use backticks instead of single (') or double (") quotes.
Output:
This is line one
This is line two
This is line three
Array Destructuring
Extract values from an array based on position.
Destructuring
Extract properties from objects based on property names.
36. What are enhanced object literals ?
Enhanced object literals are features introduced in ES6 that make it easier and cleaner to create objects.
They provide shorthand syntax and additional capabilities when defining objects.
1. Property Shorthand
If the variable name and property name are the same, you can omit the value repetition.
Before ES6:
ES6 Enhanced Syntax:
Method Shorthand
You can define methods without using the function keyword.
Before ES6:
ES6 Enhanced Syntax:
37. What is an array and how do you create one ?
An array is a special type of object used to store multiple values in a single variable.
-
It stores elements in an ordered list
-
Elements are accessed using index (starting from 0)
-
It can store different data types
Why Arrays Are Needed
-
To store collections of data
-
To iterate over multiple values
-
To manage lists like users, products, numbers, etc.
Important Characteristics
-
Arrays are zero-indexed
-
They are dynamic (can grow or shrink)
-
They are reference types
-
typeofarray returns"object"
They do not modify the original array (non-mutating) and return a new value.
1. map()
Definition
map() creates a new array by applying a function to each element of the original array.
Use Case
-
Transforming data
-
Modifying each element
Example
Each element is transformed.
2. filter()
Definition
filter() creates a new array containing only elements that satisfy a condition.
Use Case
-
Removing unwanted items
-
Selecting specific values
Example
Only elements matching the condition are kept.
3. reduce()
Definition
reduce() reduces the array to a single value by applying a function to each element.
Use Case
-
Sum of numbers
-
Counting values
-
Flattening arrays
-
Complex transformations
Syntax
Example (Sum of Numbers)
acc = accumulator
num = current value
Key Differences
-
map()→ Transforms every element -
filter()→ Selects some elements -
reduce()→ Produces a single value
An object is a non-primitive data type used to store data in key–value pairs.
-
Keys are called properties
-
Values can be any data type (string, number, array, function, etc.)
-
Objects are reference types
How to Create an Object
Using Object Literal
40. Dot notation vs bracket notation ?
1. Dot Notation
Syntax
Example
Characteristics
-
Property name must be a valid identifier
-
Cannot start with a number
-
Cannot contain spaces
-
Cleaner and more readable
-
Most commonly used
Bracket Notation
Syntax
Example
Key Differences
-
Dot notation → simple, static property access
-
Bracket notation → dynamic or special property access
-
Dot notation cannot use variables directly
-
Bracket notation can use variables
Loops are used to execute a block of code repeatedly until a specified condition becomes false.
They help:
-
Avoid code repetition
-
Iterate over arrays and objects
-
Perform repetitive tasks efficiently
Types of Loops in JavaScript
-
for loop
-
while loop
-
do...while loop
-
for...of loop
-
for...in loop
Key Differences
-
for → fixed iterations
-
while → condition-based
-
do...while → runs at least once
-
for...of → values of iterable
-
for...in → keys of object
All three are looping statements used to execute code repeatedly, but they differ in structure and condition checking.
for Loop
Used when the number of iterations is known in advance.
Syntax
Example
Characteristics
-
Initialization, condition, and update in one line
-
Condition checked before execution
-
Best for counter-based loops
2. while Loop
Executes code as long as the condition is true.
Syntax
Example
Characteristics
-
Condition checked before execution
-
Initialization and update written separately
-
Best when number of iterations is unknown
3. do...while Loop
Similar to while, but executes the block at least once.
Syntax
Example
Characteristics
-
Condition checked after execution
-
Runs at least one time, even if condition is false
Events are actions or occurrences that happen in the browser, which JavaScript can detect and respond to. They allow interaction between the user and the webpage.
Examples of Events
-
Mouse click
-
Key press
-
Form submission
-
Page load
-
Mouse hover
-
Input change
Common Event Types
-
click -
submit -
change -
mouseover -
keydown -
load
How Events Work
JavaScript listens for an event and executes a function when the event occurs.
This function is called an event handler.
Ways to Attach Events
-
Inline in HTML (not recommended)
-
Using element properties (
element.onclick) -
Using
addEventListener()(recommended)
An event listener is a function that waits for a specific event to occur on an element and executes a callback function when that event happens.
It allows JavaScript to respond to user interactions.
Syntax
Example
When the button is clicked, the function runs.
Parameters of addEventListener
-
Event type (e.g., "click", "keydown")
-
Callback function (what should run)
-
Optional options object (like capture, once, etc.)
Why Use addEventListener Instead of onclick?
-
Can attach multiple listeners to the same element
-
Provides more control (capture, bubbling)
-
Cleaner and more flexible
DOM stands for Document Object Model.
It is a programming interface provided by the browser that represents an HTML document as a tree-like structure of objects.
JavaScript uses the DOM to access and manipulate HTML elements dynamically.
How DOM Works
When a webpage loads:
-
The browser parses the HTML
-
It creates a tree structure (DOM Tree)
-
Each HTML element becomes an object (node)
-
JavaScript can access and modify these nodes
BOM stands for Browser Object Model.
It provides objects that allow JavaScript to interact with the browser itself (not just the webpage content).
While the DOM represents the HTML document, the BOM represents the browser environment.
What Does BOM Allow You To Do?
-
Access browser window
-
Control browser navigation
-
Get browser information
-
Show alerts and dialogs
-
Work with URLs
Main BOM Object
The main object in BOM is window.
Everything in the browser runs inside the window object.
Common BOM Objects
-
window
-
navigator
-
location
-
history
-
screen
console.log() is a built-in JavaScript method used to print output to the browser's console.
It is mainly used for debugging and testing code.
Syntax
Example
Why It Is Used
-
Debugging code
-
Checking variable values
-
Tracking execution flow
-
Testing logic
-
Inspecting objects and arrays
setTimeout() is a built-in browser function that executes a function after a specified delay (in milliseconds).
It is used for scheduling code to run later.
Example
After 2000 milliseconds (2 seconds), the function runs.
Using Arrow Function
Important Points
-
The delay is in milliseconds (1000 ms = 1 second)
-
It executes only once
-
It is asynchronous (non-blocking)
-
Returns a timeout ID
setInterval() is a built-in browser function that repeatedly executes a function at specified time intervals (in milliseconds).
Unlike setTimeout(), it runs continuously until stopped.
Syntax
Example
This prints the message every 2 seconds continuously.
Using Arrow Function
50. How to redirect a page using JavaScript ?
Page redirection means navigating the browser to another URL using JavaScript.
It is done using the location object (part of the BOM).
1. Using window.location.href
Redirects to the given URL
-
Keeps the current page in browser history
-
User can click Back button
2. Using window.location.assign()
Similar to
href-
Adds entry to browser history
3. Using window.location.replace()
Redirects without saving current page in history
-
User cannot go back to previous page
4. Redirect After Delay
Redirects after 3 seconds.
JSON stands for JavaScript Object Notation.
It is a lightweight data format used for storing and exchanging data between a client and a server.
JSON is language-independent but derived from JavaScript object syntax.
Why JSON Is Used
-
Sending data between frontend and backend
-
API communication
-
Storing structured data
-
Easy to read and write
JSON Structure
JSON stores data in key–value pairs.
Important Rules of JSON
-
Keys must be in double quotes
-
Strings must use double quotes
-
No functions allowed
-
No comments allowed
JSON is needed as a standard format to exchange data between systems, especially between frontend and backend.
It provides a lightweight and structured way to send and receive data.
Data Exchange Between Client and Server
JSON.stringify() is a built-in JavaScript method that converts a JavaScript object into a JSON string.
It is mainly used to send data to a server or store data in formats like localStorage.
Syntax
value→ The object to convert-
replacer(optional) → Filters properties -
space(optional) → Adds formatting/indentation
Basic Example
Why It Is Needed
-
Sending data in APIs
-
Storing objects in localStorage
-
Converting objects into transferable format
-
Logging structured data
To parse JSON means converting a JSON string into a JavaScript object.
This is done using JSON.parse().
Syntax
It takes a valid JSON string and returns a JavaScript object.
Basic Example
Now obj is a normal JavaScript object.
Why Parsing Is Needed
When data comes from:
-
APIs
-
Servers
-
localStorage
-
External files
It usually arrives as a JSON string.
We must parse it to work with it as a JavaScript object.
A cookie is a small piece of data stored in the user's browser by a website.
It is used to store information about the user and send it back to the server with every HTTP request.
Why Cookies Are Used
-
User authentication (login sessions)
-
Storing user preferences
-
Tracking user activity
-
Maintaining session information
How Cookies Work
-
Server sends a cookie to the browser
-
Browser stores it
-
Browser sends it back to the server with future requests
This helps the server recognize the user.
Creating a Cookie
Reading Cookies
This returns all cookies as a single string.
Important Cookie Attributes
-
expires → Expiry date
-
max-age → Time in seconds
-
path → URL path
-
domain → Domain name
-
secure → Only sent over HTTPS
-
HttpOnly → Not accessible via JavaScript (security feature)
Cookies are needed to store small pieces of user-specific data in the browser and maintain state between HTTP requests.
Since HTTP is stateless, cookies help websites remember users.
1. Maintaining User Sessions
When a user logs in:
-
Server creates a session
-
Sends a session ID as a cookie
-
Browser sends it back with every request
This keeps the user logged in.
2. Authentication
Cookies store authentication tokens or session IDs.
Without cookies:
-
Users would need to log in on every page request.
3. Remembering User Preferences
Cookies can store:
-
Language settings
-
Theme (dark/light mode)
-
Region selection
Example:
A website remembers your preferred language.
4. Tracking and Analytics
Used for:
-
Tracking user behavior
-
Analytics
-
Advertising personalization
5. Shopping Cart Data
E-commerce sites use cookies to:
-
Store cart items
-
Remember selections
-
Maintain checkout state
When setting a cookie, we can define additional attributes to control its behavior.
1. Expiry (expires / max-age)
Purpose
Defines how long the cookie should exist.
expires
Sets a specific expiration date.
After that date, the cookie is automatically deleted.
max-age
Sets expiry in seconds.
This cookie will expire in 1 hour (3600 seconds).
If no expiry is set:
-
It becomes a session cookie
-
Deleted when browser closes
2. Path
Purpose
Defines the URL path where the cookie is accessible.
path=/→ Cookie accessible across entire website-
path=/admin→ Cookie accessible only under/adminroute
This restricts cookie availability.
3. Secure
Purpose
Ensures the cookie is sent only over HTTPS connections.
Cookie will NOT be sent over HTTP
-
Improves security
To delete a cookie, you set its expiration date to a past date.
When the browser sees an expired cookie, it removes it.
Method 1: Using expires
Since the date is in the past, the cookie gets deleted.
Method 2: Using max-age
Setting max-age=0 immediately deletes the cookie.
Web Storage is a browser feature that allows storing data in the browser as key–value pairs.
It is used to store data on the client side without sending it to the server on every request.
Types of Web Storage
-
localStorage
-
sessionStorage
1. localStorage
-
Stores data with no expiration time
-
Data remains even after browser is closed
-
Shared across tabs of same origin
Example:
2. sessionStorage
-
Stores data only for the session
-
Data is cleared when tab is closed
-
Not shared between tabs
Example:
Important Characteristics
-
Stores only strings
-
To store objects, use JSON.stringify()
-
To retrieve objects, use JSON.parse()