Today was all about diving deeper into Objects and Arrays, two essential data structures in JavaScript. Understanding their methods and how to destructure them opened up new possibilities for simplifying code. Here’s a summary of what I learned:
Objects
Objects are collections of related properties
and methods
, allowing us to group data meaningfully.
Example Object:
let user = {
name: 'Segun',
age: 30,
email: 'ayoooladamilare@gmail.com',
location: 'Nigeria',
blogs: ['Why are you living', 'The original me'],
login: function () {
console.log(this.name, 'logged in');
},
logout: function () {
console.log(this.name, 'logged out');
},
};
JavaScript gives us built-in objects and the ability to create custom ones.
Object Methods
Object.keys(user)
: Returns an array of all the keys in the object.
console.log(Object.keys(user)); // Output: ['name', 'age', 'email', 'location', 'blogs']
Object.values(user)
: Returns an array of all the values in the object.
console.log(Object.values(user)); // Output: ['Segun', 30, 'ayoooladamilare@gmail.com', 'Nigeria', ['Why are you living', 'The original me']]
Object.seal(user)
: Prevents adding or removing properties but allows modification of existing ones.
Object.seal(user);
user.age = 31; // Allowed
user.country = 'Ghana'; // Not allowed
Object Destructuring
Destructuring simplifies extracting properties from an object.
const { name, age, email, location } = user;
console.log(name); // Output: 'Segun'
console.log(location); // Output: 'Nigeria'
Arrays
Arrays are ordered lists, making them perfect for handling sequences of data.
Example Array:
const numbers = [1, 2, 3, 4, 5];
Array Methods
.push()
: Adds elements to the end of an array and returns the new length.
numbers.push(6);
console.log(numbers); // Output: [1, 2, 3, 4, 5, 6]
.pop()
: Removes the last element from an array and returns it.
numbers.pop()
;
console.log(numbers); // Output: [1, 2, 3, 4, 5]
Array Destructuring
Similar to object destructuring, array destructuring allows for clean extraction of elements.
const colors = ['red', 'green', 'blue', 'black', 'white'];
let [first, , third] = colors;
console.log(first, third); // Output: 'red' 'blue'
We can also swap elements using destructuring:
[colors[0], colors[4]] = [colors[4], colors[0]];
console.log(colors); // Output: ['white', 'green', 'blue', 'black', 'red']
Final Thoughts
Working with objects and arrays, especially using methods and destructuring, makes coding cleaner and more intuitive. I loved how destructuring simplifies accessing data, and learning about built-in methods feels empowering.
Day 5, here I come! This journey gets better each day. Stay tuned!
Top comments (1)
This is beautiful and concise