Day 6: Objects and Arrays in JavaScript

Welcome back to our JavaScript series! Today, we'll learn about objects and arrays, which are essential for organizing and managing data in JavaScript.
Objects
Objects are collections of related data and functions. They are made up of properties (key-value pairs).
Creating and Accessing Objects
To create an object, use curly braces {} and define properties inside.
let person = {
name: 'Alice',
age: 30,
job: 'Developer'
};
// Accessing object properties
console.log(person.name); // Output: Alice
console.log(person['age']); // Output: 30
Object Methods
Objects can have methods, which are functions stored as object properties.
let person = {
name: 'Alice',
greet: function() {
console.log('Hello, ' + this.name + '!');
}
};
person.greet(); // Output: Hello, Alice!
Arrays
Arrays are used to store multiple values in a single variable. They are ordered collections of data. They store the data of same data type in the contiguous manner.
Creating and Accessing Arrays
To create an array, use square brackets [] and define elements inside.
let colors = ['red', 'green', 'blue'];
// Accessing array elements
console.log(colors[0]); // Output: red
console.log(colors[2]); // Output: blue
Array Methods
Arrays come with many built-in methods to manipulate data.
push(): Adds an element to the end of the array.
colors.push('yellow'); console.log(colors); // Output: ['red', 'green', 'blue', 'yellow']pop(): Removes the last element from the array.
colors.pop(); console.log(colors); // Output: ['red', 'green', 'blue']shift(): Removes the first element from the array.
colors.shift(); console.log(colors); // Output: ['green', 'blue']unshift(): Adds an element to the beginning of the array.
colors.unshift('purple'); console.log(colors); // Output: ['purple', 'green', 'blue']forEach(): Executes a function for each array element.
colors.forEach(function(color) { console.log(color); }); // Output: purple, green, bluemap(): Creates a new array with the results of calling a function on every element in the array.
let upperColors = colors.map(function(color) { return color.toUpperCase(); }); console.log(upperColors); // Output: ['PURPLE', 'GREEN', 'BLUE']filter(): Creates a new array with all elements that pass a test.
let shortColors = colors.filter(function(color) { return color.length <= 5; }); console.log(shortColors); // Output: ['green', 'blue']
Iterating Over Arrays
We can use loops to iterate over array elements.
let fruits = ['apple', 'banana', 'cherry'];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
// Output: apple, banana, cherry
// Using forEach
fruits.forEach(function(fruit) {
console.log(fruit);
});
// Output: apple, banana, cherry
Summary
Today, we covered objects and arrays and there various methods in JavaScript. From Tomorrow , we'll start working on Intermediate JavaScript and DOM Manipulation.




