Object Methods & Properties – JavaScript Tutorial

4/16/2025

JavaScript constructor function for creating person objects

Go Back

Object Methods & Properties – JavaScript Tutorial

In JavaScript, objects are used to store related data and functionalities. Understanding object properties and methods is essential for writing efficient and maintainable code.

In this tutorial, we'll explore how to define, access, and use properties and methods inside JavaScript objects.


JavaScript constructor function for creating person objects

What are Object Properties?

Object properties are values associated with a JavaScript object. Each property is a key-value pair.

Syntax:

const person = {
  firstName: "John",
  lastName: "Doe",
  age: 30
};
  • firstName, lastName, and age are keys (or property names).

  • Their corresponding values are "John", "Doe", and 30.

Accessing Properties

You can access properties using:

  • Dot notation

console.log(person.firstName); // John
  • Bracket notation

console.log(person["lastName"]); // Doe

Adding, Modifying & Deleting Properties

Add a property:

person.gender = "male";

Modify a property:

person.age = 31;

Delete a property:

delete person.lastName;

What are Object Methods?

Object methods are functions stored as object properties. They allow objects to perform actions.

Example:

const person = {
  firstName: "John",
  age: 30,
  greet: function() {
    console.log("Hello, my name is " + this.firstName);
  }
};

person.greet(); // Output: Hello, my name is John
  • greet is a method of the person object.

  • The this keyword refers to the object it belongs to.


Shorthand Method Syntax (ES6)

You can define methods in a shorter syntax:

const user = {
  name: "Alice",
  sayHi() {
    console.log("Hi, I'm " + this.name);
  }
};

user.sayHi(); // Output: Hi, I'm Alice

Nested Objects and Methods

Objects can contain other objects and methods:

const company = {
  name: "Tech Corp",
  employee: {
    name: "Emma",
    role: "Developer",
    introduce() {
      console.log("I'm " + this.name + ", a " + this.role);
    }
  }
};

company.employee.introduce(); // Output: I'm Emma, a Developer

Common Use-Cases for Methods

  • Calculating values

  • Handling events in web applications

  • Validating data

  • Updating internal state

Example: Method for Calculating Age

const user = {
  birthYear: 1995,
  getAge(currentYear) {
    return currentYear - this.birthYear;
  }
};

console.log(user.getAge(2025)); // Output: 30

Final Thoughts

JavaScript objects become more powerful when you understand how to work with properties and methods. By mastering these basics, you’re setting a solid foundation for working with object-oriented programming, APIs, and modern JavaScript frameworks.

In the next tutorials, we'll cover object destructuring, prototypes, and classes.

Happy coding! 🚀

Table of content