JavaScript Arrays & Objects
1. What is an Array?
Know more in DetailAn array is an ordered collection of values (elements) stored under a single variable. Each element can be accessed using a numeric index starting from 0.
Arrays can store values of any data type, including other arrays and objects.
const fruits = ["apple", "banana", "cherry"];
console.log(fruits[0]); // "apple"
2. Why Use Arrays?
- Group related data: Manage lists like students, products, tasks.
- Order matters: Keep elements in sequence and access by position.
- Iteration: Easily loop over elements with
for,forEach,map, etc. - Dynamic sizing: Add or remove elements easily.
3. Array Declaration and Basic Operations
3.1 Creating Arrays
const colors = ["red", "green", "blue"];
const empty = [];
const mixed = [1, "two", true];
3.2 Accessing & Modifying Elements
console.log(colors[1]); // "green"
colors[2] = "yellow";
console.log(colors); // ["red", "green", "yellow"]
3.3 Array Length
console.log(colors.length); // 3
4. Common Array Methods
Some important built-in methods:
push(value): Adds an element to the endpop(): Removes and returns the last elementshift(): Removes and returns the first elementunshift(value): Adds element at the startindexOf(value): Returns index of first matching element or -1slice(start, end): Returns a shallow copy subarraysplice(start, deleteCount, ...items): Add/remove elements at positionforEach(callback): Executes callback on each elementmap(callback): Returns new array with results of callbackfilter(callback): Returns array with elements passing condition
const numbers = [1, 2, 3];
numbers.push(4);
console.log(numbers); // [1, 2, 3, 4]
const evens = numbers.filter(n => n % 2 === 0);
console.log(evens); // [2, 4]
5. What is an Object?
JS built-in ObjectsAn object is a collection of key-value pairs, where keys (also called properties) are strings (or symbols), and values can be any type.
Objects allow you to group related data and functions (methods) together logically.
const person = {
name: "Alex",
age: 30,
greet: function() {
console.log("Hello, " + this.name);
}
};
console.log(person.name); // "Alex"
person.greet(); // Hello, Alex
6. Why Use Objects?
- Structure data logically: Group related properties and behavior.
- Model real-world entities: Represent people, products, settings, etc.
- Access by keys: Readable and descriptive property names.
- Store methods: Functions as object properties to represent behavior.
7. Object Declaration & Access
7.1 Creating Objects
const car = {
brand: "Toyota",
model: "Corolla",
year: 2020
};
7.2 Accessing Properties
console.log(car.brand); // Dot notation: "Toyota"
console.log(car["model"]); // Bracket notation: "Corolla"
7.3 Modifying Properties
car.year = 2021;
car["color"] = "red"; // Adding new property
console.log(car);
8. Object Methods
Object MethodsFunctions inside objects are called methods.
const calculator = {
add: function(a, b) {
return a + b;
},
multiply(a, b) {
return a * b; // shorthand method syntax
}
};
console.log(calculator.add(2, 3)); // 5
console.log(calculator.multiply(4, 5)); // 20
9. Iterating Over Arrays and Objects
9.1 Looping through Arrays
const nums = [10, 20, 30];
for (let i = 0; i < nums.length; i++) {
console.log(nums[i]);
}
// Using forEach
nums.forEach(num => console.log(num));
9.2 Looping through Objects
const user = { name: "Sam", age: 25 };
for (let key in user) {
console.log(key + ": " + user[key]);
}
10. When to Use Arrays vs Objects
- Arrays: When order matters, elements accessed by numeric index, or you have a list of similar items.
- Objects: When you want to group related named properties or represent entities with keys and values.
11. Best Practices
- Use
constfor arrays and objects to avoid accidental reassignment. - Use descriptive keys for object properties.
- Prefer array methods for immutability instead of mutating original arrays.
- Use bracket notation when keys are dynamic or not valid identifiers.
- Keep objects simple and flat; use nested objects only when necessary.
12. Array Assignments
Click to view Array Assignments
- Create an array of your five favorite movies and print the third movie.
- Add a new color to an existing array of colors.
- Remove the last element from an array and print the updated array.
- Write a function that takes an array of numbers and returns a new array with each number doubled.
- Given an array of objects representing students (name and grade), write a function to filter students who passed (grade >= 50).
- Use the map method to create an array of just student names from the array of objects.
- Write a loop to print all elements of an array in reverse order.
- Create a program to find the largest number in an array.
- Write a function that removes duplicate elements from an array.
- Create an array and sort its elements alphabetically.
- Create a function which find the maximum and minimum element in an array (without using Math.max or Math.min).
- Create a function which Count how many numbers are even and how many are odd.
- Reverse elements using a loop.
- Find the sum and average of array numbers.
- Check if a number exists in the array.
Array assignments without using any built-in Array methods
13. Object Assignments
Click to view Object Assignments
- Create an object to represent a book with properties: title, author, pages, and a method to describe the book.
- Update a property in the book object and add a new property for genre.
- Write a loop to print all keys and values of the book object.
- Create a nested object representing a company with departments as objects containing employee arrays.
- Add a method to an object that updates one of its properties.
- Write a function that takes an object and returns an array of its keys.
- Create an object and check if a given property exists in it.
- Merge two objects into a new object without modifying the originals.
- Create an object with a method that uses
thiskeyword to access properties. - Write a program to count the number of properties in an object.