Getting Started with Objects in JavaScript : Day-8

Getting Started with Objects in JavaScript

In this blogpost we will learn Objects in JavaScript. So Exlplore it..

Objects in JavaScript are a fundamental part of JavaScript, used to store collections of data and more complex entities. This post will introduce you to objects, how to create and manipulate them, and cover some common object methods.

1. What is an Object?

An object is a collection of properties, where each property is defined as a key-value pair:

//javascript
let person = {
  name: 'John',
  age: 30,
  isStudent: true
};
console.log(person); // Output: { name: 'John', age: 30, isStudent: true }

2. Creating and Accessing Objects

You can create objects using object literals, and access their properties using dot notation or bracket notation:

//javascript
let car = {  make: 'Toyota',  model: 'Corolla',  year: 2020};
// Dot notation
console.log(car.make); // Output: Toyota
// Bracket notation
console.log(car['model']); // Output: Corolla

3. Methods and Properties

Objects can also contain methods, which are functions defined within the object:

//javascript
let person = {
  name: 'Alice',
  age: 25,
  greet: function() {
    return `Hello, my name is ${this.name}`;
  }
};
console.log(person.greet()); // Output: Hello, my name is Alice

4. Nested Objects

Objects can contain other objects, allowing you to create complex data structures:

//javascript
let company = {
  name: 'TechCorp',
  employees: {
    manager: { name: 'Bob', age: 45 },
    developer: { name: 'Alice', age: 25 }
  }
};
console.log(company.employees.manager.name); // Output: Bob

5. Practical Examples

Let’s see some practical examples of using objects:

  • Updating Object Properties:
  • Deleting Object Properties:
//javascript
let person = { name: 'Dave', age: 35 };
delete person.age;
console.log(person); // Output: { name: 'Dave' }
//javascript
let person = { name: 'Charlie', age: 28 };
person.age = 29;
console.log(person.age); // Output: 29
  • Using Object Methods:
//javascript
let person = {
  name: 'Eve',
  age: 22,
  introduce: function() {
    console.log(`Hi, I'm ${this.name} and I'm ${this.age} years old.`);
  }
};
person.introduce(); // Output: Hi, I'm Eve and I'm 22 years old.

Conclusion

Objects are a powerful way to organize and manage data in JavaScript. By understanding how to create, access, and manipulate objects, you can handle more complex data structures and write more robust applications.

If you haven’t read our last day blog on the basic introduction to JavaScript, click here to read our Blogs. want to connect me on linkdin.


About The Author

Leave a Comment

Your email address will not be published. Required fields are marked *