Master the Building Blocks: Objects and Arrays in JavaScript
Contents
Introduction
Objects
Arrays
Array Methods
Projects
Bonus Tip
JavaScript thrives on organization, and two key structures enable this: Objects and Arrays. Let's dive into their power and how to use them!
- Imagine a box holding related data (properties) like name, age, and hobbies. That's an object!
- Properties are key-value pairs:
key: "value"
. Keys identify the data, and values are the actual information. - You define objects using curly braces:
{}
. - Accessing properties uses the dot notation (
object.property
) or brackets (object["property"]
).
Example:
const person = {
name: "John Doe",
age: 30,
hobbies: ["reading", "hiking"],
};
console.log(person.name); // Output: "John Doe"
console.log(person["hobbies"][1]); // Output: "hiking"
Objects Functions:
-
hasOwnProperty(propertyName)
: Determines whether an object has a property as a direct property (not inherited).
const person = { name: "Alice", age: 30 };
if (person.hasOwnProperty("age")) {
console.log("Age property exists.");
}
-
Object.assign(target, ...sources)
: Copies properties from one or more source objects to a target object.
const newPerson = Object.assign({}, person, { city: "New York" });
console.log(newPerson); // Output: { name: "Alice", age: 30, city: "New York" }
-
Object.keys(object)
: Returns an array of all own property names (enumerable string keys) of an object.
const propertyNames = Object.keys(person);
console.log(propertyNames); // Output: ["name", "age"]
Arrays:
- Think of an ordered list holding any type of data, like numbers, strings, or even other objects. That's an array!
- Elements are accessed by their index, starting from 0.
- You define arrays using square brackets:
[]
. - Accessing elements uses the index within brackets:
array[index]
.
Example:
const fruits = ["apple", "banana", "orange"];
console.log(fruits[1]); // Output: "banana"
console.log(fruits.length); // Output: 3
Mutation Methods (modify the original array):
-
push(element1, ...elementN)
: Adds one or more elements to the end of the array.
const numbers = [1, 2];
numbers.push(3, 4);
console.log(numbers); // [1, 2, 3, 4]
-
pop()
: Removes and returns the last element of the array.
const lastNumber = numbers.pop();
console.log(numbers); // [1, 2, 3]
console.log(lastNumber); // 4
-
shift()
: Removes and returns the first element of the array.
const firstNumber = numbers.shift();
console.log(numbers); // [2, 3]
console.log(firstNumber); // 1
-
unshift(element1, ...elementN)
: Adds one or more elements to the beginning of the array.
numbers.unshift(0);
console.log(numbers); // [0, 2, 3]
-
sort()
: Sorts the elements of the array in place.
numbers.sort((a, b) => a - b); // Ascending order
console.log(numbers); // [0, 2, 3]
-
reverse()
: Reverses the order of the elements in the array.
numbers.reverse();
console.log(numbers); // [3, 2, 0]
Transformation Methods (return a new array):
-
filter(callbackFunction)
: Creates a new array with elements that pass a test.
const evenNumbers = numbers.filter(number => number % 2 === 0);
console.log(evenNumbers); // [2, 0]
-
map(callbackFunction)
: Creates a new array by applying a function to each element.
const doubledNumbers = numbers.map(number => number * 2);
console.log(doubledNumbers); // [6, 4, 0]
-
reduce(callbackFunction, initialValue)
: Reduces the array to a single value.
const sum = numbers.reduce((accumulator, number) => accumulator + number, 0);
console.log(sum); // 5
-
find(callbackFunction)
: Returns the value of the first element that satisfies a test.
const firstEven = numbers.find(number => number % 2 === 0);
console.log(firstEven); // 2
-
findIndex(callbackFunction)
: Returns the index of the first element that satisfies a test.
const evenIndex = numbers.findIndex(number => number % 2 === 0);
console.log(evenIndex); // 1
-
some(callbackFunction)
: Tests whether at least one element satisfies a test.
const hasEven = numbers.some(number => number % 2 === 0);
console.log(hasEven); // true
-
every(callbackFunction)
: Tests whether all elements satisfy a test.
const allEven = numbers.every(number => number % 2 === 0);
console.log(allEven); // false
-
join(separator)
: Joins all elements of an array into a string.
const joinedString = numbers.join(", ");
console.log(joinedString); // "2, 3, 0"
Projects
Project 1: Library Management System
// Create a book object with properties and methods
function Book(title, author, genre) {
this.title = title;
this.author = author;
this.genre = genre;
this.isAvailable = true;
this.borrowBook = function() {
if (this.isAvailable) {
this.isAvailable = false;
console.log(`You've borrowed ${this.title}!`);
} else {
console.log(`Sorry, ${this.title} is currently unavailable.`);
}
};
this.returnBook = function() {
this.isAvailable = true;
console.log(`You've returned ${this.title}.`);
};
}
// Create an array to store books
const library = [];
library.push(new Book("The Lord of the Rings", "J.R.R. Tolkien", "Fantasy"));
library.push(new Book("Pride and Prejudice", "Jane Austen", "Romance"));
library.push(new Book("The Hitchhiker's Guide to the Galaxy", "Douglas Adams", "Sci-Fi"));
// Use array methods to manage books
console.log("Available books:");
library.filter(book => book.isAvailable).forEach(book => console.log(book.title));
// Example usage:
const borrowedBook = library[1].borrowBook(); // Borrow a book
library.unshift(new Book("Harry Potter and the Sorcerer's Stone", "J.K. Rowling", "Fantasy")); // Add a book
library.sort((a, b) => a.title.localeCompare(b.title)); // Sort books alphabetically
Project 2: Shopping Cart
// Create a product object with properties and methods
function Product(name, price, quantity) {
this.name = name;
this.price = price;
this.quantity = quantity;
this.addToCart = function() {
this.quantity++;
console.log(`${this.name} added to cart.`);
};
this.removeFromCart = function() {
if (this.quantity > 0) {
this.quantity--;
console.log(`${this.name} removed from cart.`);
} else {
console.log(`${this.name} is not in the cart.`);
}
};
this.calculateTotal = function() {
return this.price * this.quantity;
};
}
// Create an array to store products
const products = [];
products.push(new Product("Apple", 1.50, 0));
products.push(new Product("Banana", 0.75, 0));
products.push(new Product("Orange", 1.25, 0));
// Use array methods to manage products and cart
let cart = [];
products[0].addToCart(); // Add an apple to the cart
cart.push(products[1]); // Add a banana to the cart
console.log("Cart items:");
cart.forEach(product => console.log(product.name, product.quantity));
console.log("Total price:", cart.reduce((total, product) => total + product.calculateTotal(), 0));
Project 3: Data Analysis
// Create an array of scores
const scores = [85, 92, 78, 95, 81];
// Use array methods to analyze the data
console.log("Average score:", scores.reduce((sum, score) => sum + score, 0) / scores.length);
console.log("Highest score:", Math.max(...scores));
console.log("Lowest score:", Math.min(...scores));
console.log("Sorted scores:", scores.sort((a, b) => a - b)); // Sort ascending
console.log("Filtered scores above 90:", scores.filter(score => score > 90));
Bonus Tip: Check out MDN Web Docs for comprehensive references on objects and arrays:
Top comments (0)