JavaScript Arrays 101

Arrays store ordered collections of values—like a fruit basket or student marks—making it easy to manage lists without separate variables. They keep data organized and accessible by position.
Why Use Arrays
Without arrays, tracking multiple values means cluttering code with individual variables.
Without array:
let apple = "apple";
let banana = "banana";
let orange = "orange";
console.log(apple, banana, orange);
With array:
let fruits = ["apple", "banana", "orange"];
console.log(fruits);
Arrays group related data, simplify loops, and scale for tasks or scores effortlessly.
Creating Arrays
Declare with [] containing values, separated by commas.
let tasks = ["wake up", "code", "eat"];
let marks = [85, 92, 78, 95];
let mixed = [1, "hello", true];
Empty arrays start as let scores = []; then fill with scores[0] = 90;.
Accessing Elements
Indexes start at 0, counting positions from the left.
let fruits = ["apple", "banana", "orange"];
console.log(fruits[0]); // "apple"
console.log(fruits[2]); // "orange"
console.log(fruits[1]); // "banana"
Negative indexes don't work—stay within bounds to avoid undefined.
Updating Elements
Assign new values by index.
let marks = [85, 92, 78];
marks[1] = 95; // Update second score
marks[3] = 88; // Add fourth score
console.log(marks); // [85, 95, 78, 88]
Arrays grow or shrink dynamically as needed.
Array Length
length property counts elements.
let tasks = ["code", "test", "deploy"];
console.log(tasks.length); // 3
tasks.push("ship"); // Adds one
console.log(tasks.length); // 4
Use length - 1 for the last index.
Basic Looping
Use for loops with indexes for iteration.
let fruits = ["apple", "banana", "orange"];
for (let i = 0; i < fruits.length; i++) {
console.logFruit \({i}: \){fruits[i]});
}
// Fruit 0: apple
// Fruit 1: banana
// Fruit 2: orange
This visits every element predictably, ideal for processing lists.



