Array in JavaScript
๐ What is an Array?
An Array in JavaScript is a special variable that holds a list of values. These values can be of any type โ numbers, strings, objects, even other arrays! Arrays are ordered and indexed, starting at 0.
>>โArrays turn scattered data into structured sequences.โ ๐ง
๐ฆ Creating an Array
Basic Array Creation
let fruits = ["๐", "๐", "๐"];
let numbers = [1, 2, 3, 4, 5];
let mixed = [42, "hello", true, null];Note
๐ก You can store any data type โ even functions or objects โ in an array.
๐ข Accessing Array Elements
Use square brackets with the index to access elements.
Access Elements
let fruits = ["apple", "banana", "cherry"];
console.log(fruits[0]); // "apple"
console.log(fruits[2]); // "cherry"Note
๐ Array indices start at 0, not 1.
โ๏ธ Modifying Elements
Change Array Elements
let colors = ["red", "blue"];
colors[1] = "green";
console.log(colors); // ["red", "green"]โ Common Array Methods
- push() โ Add to end
- pop() โ Remove from end
- shift() โ Remove from start
- unshift() โ Add to start
- length โ Get number of elements
Using Array Methods
let items = [1, 2];
items.push(3); // [1, 2, 3]
items.pop(); // [1, 2]
items.unshift(0); // [0, 1, 2]
items.shift(); // [1, 2]๐ Looping Through Arrays
for Loop
let names = ["John", "Jane", "Joe"];
for (let i = 0; i < names.length; i++) {
console.log(names[i]);
}forEach Method
names.forEach(function(name) {
console.log(name);
});Note
๐ก forEach is a cleaner way to loop, especially for readability.
๐ Useful Array Methods
- map() โ Transform each item
- filter() โ Return items that match a condition
- find() โ Return the first match
- includes() โ Check if item exists
- sort() โ Sort items
Example: filter and map
let scores = [40, 80, 95, 60];
let passed = scores.filter(score => score > 60);
let doubled = scores.map(score => score * 2);๐งช Checking Arrays
Use Array.isArray() to confirm if a value is an array.
Check if it's an Array
console.log(Array.isArray([1, 2, 3])); // true
console.log(Array.isArray("hello")); // false๐ Summary Table
| Operation | Method | Description |
|---|---|---|
| Add at end | push() | Adds one or more items |
| Remove from end | pop() | Removes the last item |
| Add at start | unshift() | Adds to the front |
| Remove from start | shift() | Removes the first item |
| Loop | forEach() | Runs a function for each item |
๐ Useful Resources
>>โArrays are not just lists โ theyโre the foundation of structured, powerful data manipulation in JavaScript.โ ๐ง