Properties & Methods

In JavaScript, properties and methods are fundamental concepts used to interact with objects.

What are Properties?

Properties are values associated with an object. They describe the characteristics or attributes of that object.

Example of Properties
ObjectPropertyValue
carcolor"red"
caryear2020

What are Methods?

Methods are functions stored as object properties. They define actions that can be performed on or by the object.

Example of Methods
ObjectMethodAction
carstart()Starts the engine
carstop()Stops the engine
Illustration of properties_methods
Illustration of properties_methods

💡 Accessing Properties & Methods

Use dot notation: object.property or object.method().

📌 Deep Dive: Using Properties and Methods

JAVASCRIPT
const person = {
  name: "Alice",
  age: 25,
  greet: function() {
    return "Hello, my name is " + this.name;
  }
};

// Accessing a property
console.log(person.name); // Alice

// Calling a method
console.log(person.greet()); // Hello, my name is Alice
Output
Alice
Hello, my name is Alice

Properties vs Methods

Both belong to objects but serve different purposes:

  • Properties store data or state.
  • Methods perform actions or computations.

⚠️ Remember

Methods need parentheses () when called, while properties do not.

Common Built-in Methods

Many JavaScript objects have built-in methods. For example, strings have methods:

String Methods
MethodDescription
toUpperCase()Converts string to uppercase
slice(start, end)Extracts part of the string
includes(substring)Checks if substring exists

📌 Deep Dive: Using a String Method

JAVASCRIPT
let message = "hello world";
console.log(message.toUpperCase()); // HELLO WORLD
console.log(message.includes("world")); // true
Output
HELLO WORLD
true

💡 Summary

  • Use properties to access or store data within an object.
  • Use methods to perform actions, often manipulating properties or returning values.
  • Most JavaScript objects come with many useful built-in methods.