Arrays in JavaScript are used to store multiple values in a single variable. Instead of creating many separate variables, an array allows related data to be grouped together. Arrays are widely used to manage lists of items such as numbers, strings, or objects.
What Is an Array in JavaScript?
An array is an ordered collection of values.
Each value in an array is called an element, and each element has an index starting from 0.
Example:
Explanation:
The array fruits contains three elements.
Indexes are 0, 1, and 2.
Why Use Arrays?
Arrays help to:
-
Store multiple related values together
-
Access data using index positions
-
Loop through collections of data
-
Perform operations like adding, removing, and updating items
How to Create Arrays
Using Array Literal
Explanation:
Creates an array with three numeric values.
Using Array Constructor
Explanation:
Creates an array using the constructor syntax.
Accessing and Updating Array Elements
Explanation:
-
colors[0]accesses the first element -
colors[1] = "yellow"updates the second element
Array Length
Explanation:
Returns the total number of elements in the array.
Looping Through Arrays
Explanation:
Loops through each element using its index.
Common Array Methods (Introduction)
-
push()adds an element to the end -
pop()removes the last element -
shift()removes the first element -
unshift()adds an element to the beginning
Explanation:
Adds and removes elements from the end of the array.
Common Mistakes with Arrays
-
Using incorrect index values
-
Forgetting that indexes start from
0 -
Trying to access elements beyond array length
-
Assuming arrays can only store one data type
Summary of JavaScript Arrays
| Concept | Description |
|---|---|
| Array | Collection of multiple values |
| Index | Position of element (starts from 0) |
| length | Total elements in array |
| push/pop | Add or remove from end |
| shift/unshift | Add or remove from start |
Conclusion
Arrays in JavaScript provide a simple and efficient way to store and manage multiple values. By understanding how to create arrays, access elements, loop through data, and use basic methods, handling collections of data becomes easy and organized in JavaScript programs.