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:

JavaScript
1let fruits = ["apple", "banana", "mango"];

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

JavaScript
1let numbers = [10, 20, 30];

Explanation:
Creates an array with three numeric values.

Using Array Constructor

JavaScript
1let colors = new Array("red", "blue", "green");

Explanation:
Creates an array using the constructor syntax.


Accessing and Updating Array Elements

JavaScript
1let colors = ["red", "blue", "green"];
2
3console.log(colors[0]);
4colors[1] = "yellow";
5

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

JavaScript
1let scores = [50, 60, 70];
2
3for (let i = 0; i < scores.length; i++) {
4 console.log(scores[i]);
5}

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

JavaScript
1let list = ["a", "b"];
2list.push("c");
3list.pop();

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

ConceptDescription
ArrayCollection of multiple values
IndexPosition of element (starts from 0)
lengthTotal elements in array
push/popAdd or remove from end
shift/unshiftAdd 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.