Native JavaScript - Data Structures
Last updated
Last updated
Variables in JavaScript are containers for storing data values. They allow you to store, modify, and use information throughout your program, such as numbers, text, or more complex data types.
You can declare variables in JavaScript in several ways:
Automatically (not recommended):
This creates a global variable if not declared inside a function, but it’s considered bad practice
Using var
:
var
is function-scoped and was the traditional way to declare variables before ES6
Using let
:
let
is block-scoped and is preferred for variables that may change their value
Using const
:
const
is block-scoped and used for variables whose values should not change
You can assign a value to a variable either when you declare it or later in your code:
Or in one line:
Variables can be updated (except those declared with const
)
Variable names can contain letters, digits, underscores (_), and dollar signs ($).
Names must begin with a letter, underscore, or dollar sign.
Names are case-sensitive (myVar
and myvar
are different).
Reserved keywords (like function
or class
) cannot be used as variable names
You can use these variables elsewhere in your code:
Variables can also be reassigned (except const
):
var
Function
Yes
Yes
Old code, function-scoped vars
let
Block
Yes
No
Variables that change
const
Block
No
No
Constants (unchanging values)
Always declare variables before using them.
Prefer let
and const
over var
in modern code.
Use const
by default, and only use let
if the variable’s value will change
Variables are fundamental in JavaScript, enabling you to store and manage data efficiently throughout your programs.
Mutable and immutable are core concepts in JavaScript that describe whether a data structure can be changed after it is created.
Definition: Mutable data structures can be changed in place. Modifying them alters the original value in memory.
Examples:
Objects: You can add, remove, or change properties directly.
Arrays: You can update elements or change the array’s length.
Use Cases: Useful when you need to update data frequently or manage large, dynamic collections
Definition: Immutable data structures cannot be changed after creation. Any "modification" creates and returns a new structure, leaving the original unchanged.
Examples:
Primitive Types: Strings, numbers, booleans, null, undefined, BigInt, and Symbol are all immutable.
Immutability for Objects/Arrays: By default, objects and arrays are mutable, but you can make them immutable using techniques like Object.freeze()
or libraries such as Immutable.js.
Use Cases: Immutability is favored for predictable state management, easier debugging, safer concurrency, and functional programming patterns
Object
Yes
obj.age = 31
Alters original object
Array
Yes
arr.push(4)
Alters original array
String
No
str = 'H'
No effect; must create a new string
Number
No
num += 1
Creates a new value
Object (frozen)
No
Object.freeze(obj)
Cannot alter properties
All primitive types are immutable: Strings, numbers, booleans, null, undefined, BigInt, and Symbol
Objects and arrays are mutable by default: Their contents can be changed after creation
Immutability can be enforced: Use Object.freeze()
or third-party libraries for immutable collections
Immutability leads to safer, more predictable code: Especially useful in functional programming and state management
Summary:
Use mutable structures (objects, arrays) when in-place updates are needed and performance is critical.
Prefer immutable structures (primitives, frozen objects, or immutable libraries) for safer, more predictable code, especially in concurrent or functional programming scenarios
Arrays in JavaScript are special objects used to store ordered collections of data. They can hold multiple values—of any type—within a single variable, making them a fundamental and versatile data structure in JavaScript
Ordered Collection: Elements are stored in a specific sequence and accessed by their index (starting from 0)
Flexible Data Types: Arrays can contain numbers, strings, objects, other arrays (nested arrays), or any mix of these types
Mutable: Arrays are mutable, meaning their contents can be changed after creation (add, remove, or update elements)
Dynamic Size: Arrays can grow or shrink in size as elements are added or removed
You can create arrays using:
Array Literal Syntax (most common):
Array Constructor:
Mixed Data Types:
Access by Index:
Update by Index:
Array Length:
push()
Add element to end
fruits.push("Date")
pop()
Remove element from end
fruits.pop()
shift()
Remove element from start
fruits.shift()
unshift()
Add element to start
fruits.unshift("Apricot")
slice()
Returns a shallow copy of a portion of the array
fruits.slice(1, 3)
concat()
Joins two or more arrays
fruits.concat(["Date", "Elderberry"])
includes()
Checks if array contains a value
fruits.includes("Apple")
map()
Creates a new array by applying a function to each value
fruits.map(fruit => fruit + " Pie")
Arrays also support advanced operations like flattening nested arrays, filtering, and reducing
Arrays can contain other arrays as elements, creating multidimensional structures:
Ordered
Yes (indexed from 0)
Data Types
Any (numbers, strings, objects, arrays, etc.)
Mutable
Yes (elements can be added, removed, or changed)
Creation Methods
Array literal []
, new Array()
constructor
Common Operations
Access, update, add, remove, iterate, search, transform
Arrays are a core part of JavaScript programming, providing an efficient way to store, organize, and manipulate collections of data
A Set in JavaScript is a built-in data structure introduced in ES6 that stores a collection of unique values. Unlike arrays, Sets automatically ensure that no duplicate values are present—each value can occur only once in a Set
Unique Values Only: Any value added to a Set that already exists is ignored; duplicates are not allowed
Any Data Type: Sets can store values of any type—primitives or object references
Insertion Order: Elements in a Set are iterated in the order they were inserted
Efficient Operations: Sets provide fast access, insertion, and deletion, typically with O(1) time complexity due to internal hash table or search tree implementations
You can create a Set in two main ways:
add(value)
Adds a value to the Set
mySet.add(5)
delete(value)
Removes a value from the Set
mySet.delete(2)
has(value)
Checks if a value exists in the Set
mySet.has(3)
size
Returns the number of elements in the Set
mySet.size
clear()
Removes all elements from the Set
mySet.clear()
forEach()
Iterates over each value in the Set
mySet.forEach(val => ...)
You can also iterate over a Set using a for...of
loop:
When you need to store a collection of unique values.
When you want fast checks for the presence of a value.
When you need to eliminate duplicates from an array
A Map in JavaScript is a built-in data structure that stores key-value pairs, where each key is unique and can be of any data type—including objects, functions, and primitive values. Maps were introduced in ES6 and are designed to provide efficient and flexible key-based data storage and retrieval
Unique Keys: Each key in a Map must be unique; duplicate keys are not allowed.
Any Data Type as Key: Unlike plain objects (which only allow strings and symbols as keys), Maps allow keys of any type, including objects, arrays, and functions
Insertion Order: Maps maintain the order of elements based on the sequence in which they were added. Iterating over a Map will yield entries in their original insertion order
Size Property: The size
property returns the number of key-value pairs in the Map
Direct Iteration: Maps are directly iterable, making it easy to loop over keys, values, or entries
The set(key, value)
method adds or updates a key-value pair
The get(key)
method retrieves the value associated with a key
The has(key)
method checks if a key exists in the Map
Use delete(key)
to remove a specific entry and clear()
to remove all entries
You can iterate over a Map’s entries, keys, or values:
When you need to use objects or other non-string types as keys.
When you require guaranteed insertion order.
When you need frequent additions and removals of key-value pairs with efficient performance
JavaScript provides several built-in data structures for storing and managing collections of data. The most commonly used are Array, Map, and Set. Each has distinct characteristics and is best suited for specific use cases.
Structure
Ordered list of values (indexed)
Collection of key-value pairs
Unordered collection of unique values
Key/Index
Integer indices (0, 1, 2, ...)
Any data type as key
No keys; only values
Value Types
Any
Any
Any
Duplicates
Allowed
Keys must be unique
Not allowed (all values unique)
Order
Maintains insertion order
Maintains insertion order
Maintains insertion order
Access
By index (e.g., arr)
By key (e.g., map.get(key))
By value (e.g., set.has(value))
Iteration
for
, forEach
, for...of
forEach
, for...of
(entries/keys/values)
forEach
, for...of
Common Use Case
Lists, arrays of data, ordered items
Fast key-value lookup, dynamic keys
Unique values, removing duplicates
Performance
Fast random access by index; slower search by value
Fast key-based access (O(1)), efficient add/remove
Fast existence checks (O(1)), efficient add/remove
Example
[1][2][3]
new Map([[1, 'a'], [2, 'b']])
new Set([1,[2][3])
Array
Use when you need an ordered list of items, possibly with duplicates, and access by position (index) is important.
Example: List of user IDs, ordered tasks, etc.
Map
Use when you need to associate unique keys (of any type) with values, and require fast lookup, insertion, or deletion by key.
Example: Storing user data by user ID, caching, dictionaries
Set
Use when you need to store unique values and quickly check for existence, or when you want to remove duplicates from a collection.
Example: Unique tags, filtering duplicates from an array
Arrays are best for ordered collections where the position of each element matters and duplicates are allowed.
Maps are optimized for storing key-value pairs, where keys can be any data type and are unique. They provide efficient, direct access to values via keys
Sets automatically enforce uniqueness among their values and are ideal for collections where duplicates should be eliminated or prevented
Array: Ordered, indexed, allows duplicates.
Map: Key-value pairs, unique keys, any type as key, efficient lookups.
Set: Unique values only, fast existence checks, no key-value pairs.
Choosing the right data structure depends on your specific requirements for ordering, uniqueness, and how you intend to access or modify the data