HomeJAVASCRIPTWhat are object properties and methods?

What are object properties and methods?

In JavaScript (and in general OOP),

👉 Objects are collections of data (properties) and behavior (methods).


1. Object Properties

  • Definition: Properties are key–value pairs that hold data about the object.
  • Analogy: Think of them as variables that belong to the object.
  • Syntax:
let person = {
  name: "Himanshu",   // property (string)
  age: 27,            // property (number)
  isDeveloper: true   // property (boolean)
};

console.log(person.name); // "Himanshu"
console.log(person.age);  // 27

✅ Properties describe the state or characteristics of the object.


2. Object Methods

  • Definition: Methods are functions inside objects that define actions or behavior.
  • Analogy: Think of them as functions that belong to the object.
  • Syntax:
let person = {
  name: "Himanshu",
  age: 27,
  greet: function () {
    console.log("Hello, my name is " + this.name);
  }
};

person.greet(); // "Hello, my name is Himanshu"

✅ Methods describe what the object can do.
✅ The keyword this refers to the current object.


Quick Example Combining Both

let car = {
  brand: "Tesla",        // property
  model: "Model S",      // property
  start: function() {    // method
    console.log(this.brand + " " + this.model + " is starting...");
  }
};

console.log(car.brand); // "Tesla"  (property)
car.start();            // "Tesla Model S is starting..." (method)

🔑 Summary:

  • Properties = data/attributes of the object
  • Methods = functions/behavior of the object

Share: 

No comments yet! You be the first to comment.

Leave a Reply

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