A JavaScript array is an object type that can store multiple values in an ordered list.
- Arrays are zero-indexed.
- Can store different types of data: numbers, strings, objects, other arrays, etc.
- Arrays are dynamic (length can change).
🔹 Note: Arrays in JS are objects, but with special behavior for indexing and length.
1. Creating Arrays
1.1 Array Literal
An array literal is the simplest and most common way to create an array using square brackets [].
Syntax:
Examples:
Characteristics:
-
Simple & readable – ideal for most use cases.
-
Can contain any type of value, including other arrays (nested arrays).
-
Length automatically adjusts when elements are added or removed.
Adding/Removing with Array Literal:
✅ Recommended: Use Array Literal unless you have a very specific reason to use the constructor.
1.2 Array Constructor
JavaScript provides an Array constructor (new Array()) to create arrays.
Syntax:
Examples:
Edge Case (Important!):
-
Single numeric argument is treated as array length, not an element.
-
If you pass more than one number, it creates an array of those numbers:
Characteristics:
- Can create arrays with predefined length.
- Can lead to confusing behavior if a single number is passed.
- Less readable compared to literals.
Adding elements later:
2. Accessing Array Elements
Arrays are zero-indexed, meaning the first element is at index 0.
Access by Index
Access Last Element
3. Modifying Array Elements
You can change existing elements by referencing their index.
Adding New Element at a Specific Index
Using push() and unshift() to Add
Removing Elements
- pop() – removes last element
- shift() – removes first element
4. Array Length
The length property gives the number of elements in the array.
Modify Length
You can truncate or expand an array by changing its length.
⚠ Expanding length adds empty slots, not undefined values.
5. Looping Through Array Elements
Or using for...of:
