What is an Array?
- An array is used to store multiple values in a single variable.
- An array can store values of the same or different data types.
- Each individual value stored inside an array is called an element.
Without Array:
let student1 = "Abi";
let student2 = "Max";
let student3 = "Rohith";
let student4 = "virat";
let student5 = "ABD";
Here, separate variables are used to store each student name.
With Array:
let students = ["Abi", "Max", "Rohith", "virat", "ABD"];
Here, all the student names are stored together in a single array called students.
Real-World Example
An array can be compared to a school bag.
A school bag is a single container that can hold multiple items such as:
Book
Pen
Pencil
Eraser
Scale
Similarly, an array is a collection of values that can store multiple values together.
let schoolBag = ["Book", "Pen", "Pencil", "Eraser", "Scale"];
Each individual value inside the array is called an element.
For example:
let fruits = ["Apple", "Banana", "Mango"];
Here:
-
"Apple"→ Element -
"Banana"→ Element -
"Mango"→ Element
Different Data Types in an Array
JavaScript arrays can store different types of values in the same array.
let data = ["Arun", 20, true, 25.5];
Here:
-
"Arun"→ String -
20→ Number -
true→ Boolean -
25.5→ Number
So, an array does not have to contain only one type of value.
In simple words, an array is a way to store multiple values of the same or different data types together in a single variable.
Why do we use Arrays?
- To store multiple values in a single variable.
- To keep related data organized together.
- To avoid creating separate variables for every value.
- To make multiple values easier to manage.
- Arrays can be used with loops to process multiple values.
- Arrays are commonly used to store collections such as student names, marks, products, prices, and scores.
Example:
let marks = [80, 75, 90, 85, 70];
Here, multiple marks are stored together in the marks array.
Arrays are widely used in JavaScript applications whenever a collection of values needs to be stored and processed.
Top comments (0)