- Arrays are one of the most commonly used data structures in JavaScript.
- They allow us to store multiple values in a single variable, making code cleaner and easier to manage.
- Instead of creating many variables, arrays help group related values together.
For example, rather than writing:
let mark1 = 85;
let mark2 = 90;
let mark3 = 78;
we can write:
let marks = [85, 90, 78];
This makes the code more organized and scalable.
What is an Array?
An array is a special type of object in JavaScript used to store an ordered collection of values.
let fruits = ["apple", "banana", "orange"];
Here:
-
"apple"is at index0 -
"banana"is at index1 -
"orange"is at index2
JavaScript arrays always start indexing from 0.
Accessing Array Elements
You can access elements using their index.
let fruits = ["apple", "banana", "orange"];
console.log(fruits[0]);
console.log(fruits[1]);
Output:
apple
banana
Updating Values
You can modify any value in the array.
let numbers = [10, 20, 30];
numbers[1] = 50;
console.log(numbers);
Output:
[10, 50, 30]
Array Length
To find the number of elements in an array, use .length.
let colors = ["red", "blue", "green"];
console.log(colors.length);
Output:
3
Looping Through Arrays
Arrays are commonly used with loops.
let nums = [1, 2, 3, 4, 5];
for (let i = 0; i < nums.length; i++) {
console.log(nums[i]);
}
- This prints each element one by one.
Important Built-in Array Methods(To be discussed)
push() – Add element at the end
let arr = [1, 2, 3];
arr.push(4);
console.log(arr);
Output:
[1, 2, 3, 4]
pop() – Remove last element
arr.pop();
shift() – Remove first element
arr.shift();
unshift() – Add element at the beginning
arr.unshift(0);
Arrays Can Store Multiple Data Types
JavaScript arrays can hold different types of values.
let mixed = [10, "hello", true, 25.5];
- This flexibility is one of JavaScript’s strengths.
Is Array a Data Type?
Arrays are technically objects in JavaScript.
typeof [1, 2, 3]
Output:
"object"
To specifically check for arrays:
Array.isArray([1, 2, 3]);
Output:
true
Conclusion
- Arrays are essential in JavaScript programming.
- They help manage collections of data efficiently and are widely used in web development, data handling, and algorithms.
Top comments (0)