๐Ÿงฑ JavaScript Objects & OOP
Estimated reading: 5 minutes 10 views

๐Ÿง  JavaScript Object Properties and Methods: A Comprehensive Guide

In JavaScript, objects are one of the most essential data types. An object is a collection of properties, and each property has a key (or name) and a value associated with it. In addition to properties, objects also have methods, which are functions that are associated with the object and can manipulate its properties or perform other tasks. Understanding how to work with object properties and methods is crucial for creating robust JavaScript applications.

In this guide, weโ€™ll explore:

  • What object properties and methods are
  • How to define and access them
  • Practical examples to help you master object properties and methods in JavaScript

๐Ÿ“Œ What Are JavaScript Object Properties and Methods?

Object Properties:

Properties are key-value pairs that belong to an object. The key is always a string (or symbol), and the value can be any valid data type (string, number, array, function, etc.).

Example of an Object with Properties:

const person = {
  firstName: "John",
  lastName: "Doe",
  age: 30
};

Here, firstName, lastName, and age are properties of the person object. Each property has a corresponding value.

Accessing Object Properties:

You can access object properties using dot notation or bracket notation.

  • Dot Notation: console.log(person.firstName); // John
  • Bracket Notation: console.log(person["age"]); // 30

Object Methods:

Methods are functions stored as object properties. These functions can access and manipulate the objectโ€™s properties.

Example of an Object with Methods:

const person = {
  firstName: "John",
  lastName: "Doe",
  age: 30,
  fullName: function() {
    return this.firstName + " " + this.lastName;
  }
};

In this case, fullName is a method of the person object that returns the full name of the person. The this keyword refers to the current object.

Invoking Object Methods:

You invoke object methods the same way you access properties:

console.log(person.fullName()); // John Doe

๐Ÿ“˜ Accessing and Modifying Object Properties

1. Dot Notation:

The most common way to access properties is via dot notation, where the property name is directly written after the object.

const car = {
  make: "Toyota",
  model: "Corolla",
  year: 2022
};
console.log(car.make); // Output: Toyota

2. Bracket Notation:

Bracket notation is useful when property names are dynamic, or if they contain spaces or special characters. Itโ€™s also required when the property name is stored in a variable.

const car = {
  "car make": "Toyota",
  model: "Corolla"
};
console.log(car["car make"]); // Output: Toyota

let propName = "model";
console.log(car[propName]); // Output: Corolla

Modifying Properties:

You can modify object properties using both dot and bracket notation.

car.year = 2023; // Modifying property with dot notation
car["model"] = "Camry"; // Modifying property with bracket notation

โš™๏ธ Adding and Deleting Object Properties

Adding Properties:

You can add new properties to an object after its creation using either dot or bracket notation.

car.color = "Blue"; // Adding a property with dot notation
car["owner"] = "Alice"; // Adding a property with bracket notation

Deleting Properties:

To delete a property from an object, you can use the delete operator.

delete car.color; // Removes the 'color' property
console.log(car.color); // Output: undefined

๐Ÿงฉ Object Methods: Adding and Using

Adding Methods to Objects:

You can define methods inside an object just like you add properties. These methods can access the objectโ€™s properties and perform operations.

Example of Object with Method:

const car = {
  make: "Toyota",
  model: "Corolla",
  year: 2022,
  displayInfo: function() {
    return `Car: ${this.make} ${this.model}, Year: ${this.year}`;
  }
};
console.log(car.displayInfo()); // Output: Car: Toyota Corolla, Year: 2022

Using Arrow Functions in Object Methods:

You can also use arrow functions as methods, but be cautious as they do not bind their own this. Instead, they inherit it from the outer lexical context.

Example of Arrow Function in Object:

const car = {
  make: "Toyota",
  model: "Corolla",
  year: 2022,
  displayInfo: () => {
    return `Car: ${this.make} ${this.model}, Year: ${this.year}`;
  }
};
console.log(car.displayInfo()); // Output: Car: undefined undefined, Year: undefined

In this case, this does not refer to the car object as expected, and the properties are undefined.


๐Ÿ’ก Best Practices for Using Object Properties and Methods

  • Use dot notation when possible: It’s cleaner and easier to read.
  • Use bracket notation for dynamic property names: When property names are variables or contain spaces/special characters.
  • Keep methods concise: Make methods short and focused on one task for better maintainability.
  • Avoid using arrow functions for methods: When using this, prefer traditional function expressions for methods.
  • Use Object.freeze(): To prevent changes to an object, use Object.freeze() to make the object immutable.
const person = Object.freeze({
  name: "Alice",
  age: 30
});
person.age = 31; // This will have no effect
console.log(person.age); // Output: 30

๐Ÿ“Œ Conclusion: Mastering Object Properties and Methods

In this guide, we have covered the essentials of JavaScript object properties and methods, including how to access, modify, and delete properties, as well as define and use methods. Understanding these fundamentals will enable you to create dynamic and interactive web applications.

To further enhance your skills, you may want to dive deeper into topics such as object inheritance, prototype chains, and ES6 features like classes and getter/setter methods.


โ“ FAQ: Common Questions on JavaScript Object Properties and Methods

โ“ What is the difference between properties and methods in an object?

  • Properties are key-value pairs that hold data.
  • Methods are functions that perform actions using the objectโ€™s properties.

โ“ Can I store a function as a property of an object?

Yes, functions are first-class objects in JavaScript, so you can store them as properties of an object.

โ“ What does the this keyword refer to in object methods?

In regular functions, this refers to the object from which the method was called. However, in arrow functions, this is inherited from the outer scope, not the object.

โ“ Can I delete object properties dynamically?

Yes, you can use the delete operator to remove properties from an object, but it is generally not recommended for performance reasons.


Share Now :

Leave a Reply

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

Share

JavaScript โ€” Object Properties / Methods

Or Copy Link

CONTENTS
Scroll to Top