-
-
Notifications
You must be signed in to change notification settings - Fork 2
JavaScript Beginner Part3
Arrays and objects are the two most important data structures in JavaScript. Arrays store ordered collections of values, while objects store collections of key-value pairs. Together, they form the foundation of data manipulation in JavaScript.
Arrays are ordered collections of values. Think of them like numbered lists where each item has a specific position.
// Array of strings
let fruits = ["apple", "banana", "cherry"];
// Array of numbers
let numbers = [1, 2, 3, 4, 5];
// Array of mixed types (valid but not recommended)
let mixed = ["hello", 42, true, null];
// Empty array
let empty = [];
// Array with constructor
let colors = new Array("red", "green", "blue");
// Array of arrays (nested arrays)
let matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];let fruits = ["apple", "banana", "cherry", "date"];
// Access by index (0-based)
console.log(fruits[0]); // "apple"
console.log(fruits[1]); // "banana"
console.log(fruits[2]); // "cherry"
// Last element
console.log(fruits[fruits.length - 1]); // "date"
// Out of bounds returns undefined
console.log(fruits[10]); // undefined
// Change element by index
fruits[1] = "blueberry";
console.log(fruits); // ["apple", "blueberry", "cherry", "date"]let numbers = [1, 2, 3];
// length property
console.log(numbers.length); // 3
// push() - add to end
numbers.push(4);
console.log(numbers); // [1, 2, 3, 4]
// pop() - remove from end
let removed = numbers.pop();
console.log(removed); // 4
console.log(numbers); // [1, 2, 3]
// unshift() - add to beginning
numbers.unshift(0);
console.log(numbers); // [0, 1, 2, 3]
// shift() - remove from beginning
let first = numbers.shift();
console.log(first); // 0
console.log(numbers); // [1, 2, 3]let colors = ["red", "green"];
// Add multiple elements
colors.push("blue", "yellow");
console.log(colors); // ["red", "green", "blue", "yellow"]
// Add at specific position using splice()
colors.splice(1, 0, "orange", "purple");
console.log(colors); // ["red", "orange", "purple", "green", "blue", "yellow"]
// index 1, delete 0, add orange & purple
// Remove elements using splice()
let removedColors = colors.splice(1, 2);
console.log(removedColors); // ["orange", "purple"]
console.log(colors); // ["red", "green", "blue", "yellow"]
// Replace elements
colors.splice(2, 1, "cyan");
console.log(colors); // ["red", "green", "cyan", "yellow"]
// Clear entire array
colors.length = 0;
console.log(colors); // []
// Or use splice to clear
colors.splice(0);
console.log(colors); // []let numbers = [1, 2, 3, 4, 5, 3, 6];
// indexOf() - first occurrence
console.log(numbers.indexOf(3)); // 2
console.log(numbers.indexOf(99)); // -1 (not found)
// lastIndexOf() - last occurrence
console.log(numbers.lastIndexOf(3)); // 5
// includes() - check if exists
console.log(numbers.includes(3)); // true
console.log(numbers.includes(99)); // false
// find() - find first matching element
let people = [
{ name: "Alice", age: 25 },
{ name: "Bob", age: 30 },
{ name: "Charlie", age: 35 }
];
let found = people.find(person => person.age > 28);
console.log(found); // { name: "Bob", age: 30 }
// findIndex() - find index of first match
let foundIndex = people.findIndex(person => person.name === "Charlie");
console.log(foundIndex); // 2let numbers = [1, 2, 3, 4, 5];
// map() - transform each element
let doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6, 8, 10]
// filter() - keep elements that pass test
let evens = numbers.filter(num => num % 2 === 0);
console.log(evens); // [2, 4]
// reduce() - combine into single value
let sum = numbers.reduce((acc, num) => acc + num, 0);
console.log(sum); // 15
// Chaining methods
let result = numbers
.filter(num => num > 2)
.map(num => num * 2);
console.log(result); // [6, 8, 10]let fruits = ["banana", "apple", "cherry", "date"];
// sort() - alphabetical (modifies original)
fruits.sort();
console.log(fruits); // ["apple", "banana", "cherry", "date"]
// sort() with custom function
let numbers = [10, 2, 5, 1, 20];
numbers.sort((a, b) => a - b); // ascending
console.log(numbers); // [1, 2, 5, 10, 20]
numbers.sort((a, b) => b - a); // descending
console.log(numbers); // [20, 10, 5, 2, 1]
// reverse() - reverses array
let reversed = [1, 2, 3].reverse();
console.log(reversed); // [3, 2, 1]let fruits = ["apple", "banana", "cherry"];
// for loop
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
// for...of (recommended)
for (let fruit of fruits) {
console.log(fruit);
}
// forEach()
fruits.forEach((fruit, index) => {
console.log(index + ": " + fruit);
});
// for...in (gives indices)
for (let index in fruits) {
console.log(index + ": " + fruits[index]);
}Objects store collections of key-value pairs. They're perfect for representing entities with multiple properties.
// Object literal (most common)
let person = {
name: "Alice",
age: 25,
city: "New York"
};
// Object with constructor
let car = new Object();
car.brand = "Toyota";
car.year = 2022;
// Object with computed property names
let key = "email";
let user = {
name: "Bob",
[key]: "bob@example.com" // email: "bob@example.com"
};
// Nested objects
let company = {
name: "TechCorp",
location: {
city: "San Francisco",
country: "USA"
}
};let person = {
name: "Alice",
age: 25,
city: "New York"
};
// Dot notation (recommended)
console.log(person.name); // "Alice"
console.log(person.age); // 25
// Bracket notation
console.log(person["name"]); // "Alice"
console.log(person["age"]); // 25
// Computed property access
let property = "city";
console.log(person[property]); // "New York"
// Access nested properties
let company = {
name: "TechCorp",
location: {
city: "San Francisco"
}
};
console.log(company.location.city); // "San Francisco"
console.log(company["location"]["city"]); // "San Francisco"
// Optional chaining (?.)
console.log(company?.location?.city); // "San Francisco"
console.log(company?.CEO?.name); // undefined (no error)let person = {
name: "Alice",
age: 25
};
// Add new properties
person.city = "New York";
person.email = "alice@example.com";
console.log(person); // { name: "Alice", age: 25, city: "New York", email: "alice@example.com" }
// Modify existing properties
person.age = 26;
console.log(person.age); // 26
// Delete properties
delete person.email;
console.log(person); // { name: "Alice", age: 25, city: "New York" }
// Check if property exists
console.log("name" in person); // true
console.log("email" in person); // false
// Object methods
console.log(Object.keys(person)); // ["name", "age", "city"]
console.log(Object.values(person)); // ["Alice", 25, "New York"]
console.log(Object.entries(person)); // [["name", "Alice"], ["age", 25], ["city", "New York"]]let person1 = { name: "Alice", age: 25 };
let person2 = { name: "Bob", age: 30 };
// Object.assign() - copy/merge objects
let clone = Object.assign({}, person1);
console.log(clone); // { name: "Alice", age: 25 }
let combined = Object.assign({}, person1, person2);
console.log(combined); // { name: "Bob", age: 30 } (person2 overwrites)
// Spread operator (modern way)
let clone2 = { ...person1 };
let combined2 = { ...person1, ...person2 };
// Object.freeze() - prevent modifications
let frozen = Object.freeze({ name: "Alice" });
// frozen.name = "Bob"; // Error in strict mode, silently fails otherwise
console.log(frozen.name); // "Alice"
// Object.seal() - allow modifications but not additions/deletions
let sealed = Object.seal({ name: "Alice" });
sealed.name = "Bob"; // Works
// delete sealed.name; // Error
sealed.age = 25; // Ignored (can't add new properties)let person = {
name: "Alice",
age: 25,
city: "New York"
};
// Basic destructuring
let { name, age } = person;
console.log(name); // "Alice"
console.log(age); // 25
// Rename variables
let { name: personName, age: personAge } = person;
console.log(personName); // "Alice"
// Default values
let { name, country = "USA" } = person;
console.log(country); // "USA"
// Nested destructuring
let company = {
name: "TechCorp",
location: {
city: "San Francisco",
country: "USA"
}
};
let { location: { city } } = company;
console.log(city); // "San Francisco"
// In function parameters
function greet({ name, age }) {
console.log(`Hello, ${name}! You are ${age} years old.`);
}
greet(person); // "Hello, Alice! You are 25 years old."let person = {
name: "Alice",
age: 25,
// Method
greet: function() {
console.log("Hello, " + this.name + "!");
},
// Shorthand method (ES6)
introduce() {
console.log(`I am ${this.name} and I am ${this.age} years old.`);
},
// Arrow function in object (be careful!)
// Arrow functions don't have their own 'this'
getAge: () => {
console.log(this.age); // 'this' is NOT person!
}
};
person.greet(); // "Hello, Alice!"
person.introduce(); // "I am Alice and I am 25 years old."This is one of the most common patterns in JavaScript development:
let users = [
{ id: 1, name: "Alice", email: "alice@example.com", role: "admin" },
{ id: 2, name: "Bob", email: "bob@example.com", role: "user" },
{ id: 3, name: "Charlie", email: "charlie@example.com", role: "user" },
{ id: 4, name: "Diana", email: "diana@example.com", role: "moderator" }
];
// Find specific user
let admin = users.find(user => user.role === "admin");
console.log(admin.name); // "Alice"
// Get all users with a specific role
let regularUsers = users.filter(user => user.role === "user");
console.log(regularUsers.length); // 2
// Get array of all names
let names = users.map(user => user.name);
console.log(names); // ["Alice", "Bob", "Charlie", "Diana"]
// Get user IDs
let ids = users.map(user => user.id);
console.log(ids); // [1, 2, 3, 4]
// Check if all users have valid emails
let allHaveEmails = users.every(user => user.email.includes("@"));
console.log(allHaveEmails); // true
// Check if any user is an admin
let hasAdmin = users.some(user => user.role === "admin");
console.log(hasAdmin); // true
// Sort users by name
let sortedByName = [...users].sort((a, b) => a.name.localeCompare(b.name));
console.log(sortedByName.map(u => u.name)); // ["Alice", "Bob", "Charlie", "Diana"]
// Group users by role
let groupedByRole = users.reduce((acc, user) => {
if (!acc[user.role]) {
acc[user.role] = [];
}
acc[user.role].push(user);
return acc;
}, {});
console.log(groupedByRole);
// {
// admin: [{ id: 1, name: "Alice", ... }],
// user: [{ id: 2, ... }, { id: 3, ... }],
// moderator: [{ id: 4, ... }]
// }Create an array of your 5 favorite foods and:
- Print the third item
- Add a new food to the end
- Remove the first food
- Print the array length
let foods = ["pizza", "sushi", "tacos", "burger", "pasta"];
console.log(foods[2]); // "tacos"
foods.push("ice cream");
foods.shift();
console.log(foods.length); // 5Given the array [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]:
- Filter even numbers
- Square each number
- Sum all numbers
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let evens = numbers.filter(n => n % 2 === 0);
console.log(evens); // [2, 4, 6, 8, 10]
let squared = numbers.map(n => n ** 2);
console.log(squared); // [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
let sum = numbers.reduce((acc, n) => acc + n, 0);
console.log(sum); // 55Create an object representing a book with title, author, year, and isRead properties. Then:
- Add a genre property
- Mark it as read
- Print all properties
let book = {
title: "The Great Gatsby",
author: "F. Scott Fitzgerald",
year: 1925,
isRead: false
};
book.genre = "Classic Fiction";
book.isRead = true;
console.log(Object.entries(book));
// [["title", "The Great Gatsby"], ["author", "F. Scott Fitzgerald"], ...]Given this data:
let products = [
{ name: "Laptop", price: 999, inStock: true },
{ name: "Phone", price: 699, inStock: true },
{ name: "Tablet", price: 499, inStock: false },
{ name: "Watch", price: 299, inStock: true }
];Find:
- All products in stock
- Total value of all products
- Most expensive product
let inStock = products.filter(p => p.inStock);
console.log(inStock); // Laptop, Phone, Watch
let totalValue = products.reduce((sum, p) => sum + p.price, 0);
console.log(totalValue); // 2496
let mostExpensive = products.reduce((max, p) => p.price > max.price ? p : max);
console.log(mostExpensive.name); // "Laptop"| Topic | Key Points |
|---|---|
| Arrays | Ordered collections, 0-indexed, use for lists |
| Array Methods | push, pop, shift, unshift, splice, map, filter, reduce |
| Objects | Key-value pairs, use for entities |
| Object Access | Dot notation and bracket notation |
| Destructuring | Extract values with { key } syntax |
| Array of Objects | Common pattern, chain methods for data processing |
Continue to the Intermediate Guide where we'll cover more advanced topics like ES6+ features, async programming, and DOM manipulation.
// Arrays
let arr = [1, 2, 3];
arr.push(4); // Add to end
arr.pop(); // Remove from end
arr.unshift(0); // Add to beginning
arr.shift(); // Remove from beginning
arr.map(x => x*2); // Transform
arr.filter(x => x>1); // Filter
arr.reduce((a,b) => a+b); // Reduce
// Objects
let obj = { a: 1, b: 2 };
obj.c = 3; // Add property
delete obj.c; // Remove property
Object.keys(obj); // ["a", "b"]
Object.values(obj); // [1, 2]
let { a, b } = obj; // Destructure