JavaScript provides powerful ways to store and manage collections of related data: Arrays for ordered lists and Objects for unordered key-value pairs.
7.1. Arrays: Creation, Access, Properties, and Methods
An Array is a special type of object used to store ordered collections of items. Items can be of any data type.
-
Creating Arrays
let colors = ["red", "green", "blue"]; // Array literal (most common) let numbers = new Array(1, 2, 3); // Using Array constructor let emptyArray = []; -
Accessing Array Elements (Indexing): Elements are accessed using their zero-based index.
console.log(colors[0]); // Output: "red" console.log(colors[2]); // Output: "blue" console.log(colors[3]); // Output: undefined (index out of bounds) -
Array Properties
-
length: Returns the number of elements in the array.console.log(colors.length); // Output: 3
-
-
Common Array Methods
-
push(): Adds one or more elements to the end.colors.push("yellow"); // colors is now ["red", "green", "blue", "yellow"] -
pop(): Removes the last element and returns it.let lastColor = colors.pop(); // lastColor is "yellow", colors is ["red", "green", "blue"] -
shift(): Removes the first element and returns it.let firstColor = colors.shift(); // firstColor is "red", colors is ["green", "blue"] -
unshift(): Adds one or more elements to the beginning.colors.unshift("purple"); // colors is now ["purple", "green", "blue"] -
splice(start, deleteCount, item1, ...): Changes the contents of an array by removing or replacing existing elements and/or adding new elements.let fruits = ["apple", "banana", "cherry", "date"]; fruits.splice(1, 2, "grape", "kiwi"); // Removes "banana", "cherry"; adds "grape", "kiwi" console.log(fruits); // Output: ["apple", "grape", "kiwi", "date"] -
slice(start, end): Returns a shallow copy of a portion of an array into a new array. Does not modify the original.let slicedFruits = fruits.slice(1, 3); // ["grape", "kiwi"] console.log(fruits); // Original array unchanged -
indexOf(): Returns the first index at which a given element can be found, or -1 if not present.console.log(colors.indexOf("green")); // Output: 1 -
includes(): Checks if an array includes a certain value, returningtrueorfalse.console.log(colors.includes("blue")); // Output: true
-
7.2. Iterating Arrays
You can loop through array elements in several ways:
-
forloop (traditional):for (let i = 0; i < colors.length; i++) { console.log(colors[i]); } -
forEach()method (ES5+): Executes a provided function once for each array element.colors.forEach(function(color, index) { console.log(`${index}: ${color}`); }); // Or with arrow function: colors.forEach((color) => console.log(color)); -
for...ofloop (ES6+): Iterates over the values of an iterable object (like an array).for (let color of colors) { console.log(color); }
7.3. Objects: Creation, Accessing Properties
An Object is a collection of unordered key-value pairs (properties). It's used to store structured data.
-
Creating Objects (Object Literals - most common)
let person = { firstName: "Alice", lastName: "Smith", age: 30, isStudent: false }; -
Accessing Object Properties
-
Dot Notation (preferred for valid identifiers)
console.log(person.firstName); // Output: "Alice" -
Bracket Notation (for dynamic keys or keys with special characters/spaces):
console.log(person["lastName"]); // Output: "Smith" let prop = "age"; console.log(person[prop]); // Output: 30
-
7.4. Adding, Modifying, and Deleting Object Properties
-
Adding Properties
person.email = "[email protected]"; person["city"] = "New York"; console.log(person); // Now includes email and city -
Modifying Properties
person.age = 31; console.log(person.age); // Output: 31 -
Deleting Properties:
delete person.isStudent; console.log(person); // isStudent property is removed
7.5. Iterating Objects
You can loop through object properties:
-
for...inloop: Iterates over the enumerable properties of an object (including inherited ones, so often used withhasOwnProperty).for (let key in person) { if (person.hasOwnProperty(key)) { // Good practice to check console.log(`${key}: ${person[key]}`); } } -
Object.keys()(ES5+): Returns an array of an object's own enumerable property names.Object.keys(person).forEach(key => { console.log(`${key}: ${person[key]}`); }); -
Object.values()(ES8): Returns an array of an object's own enumerable property values.Object.values(person).forEach(value => { console.log(value); }); -
Object.entries()(ES8): Returns an array of[key, value]pairs for an object's own enumerable properties.Object.entries(person).forEach(([key, value]) => { console.log(`${key}: ${value}`); });
Join the conversation! Your thoughts help the community grow.