Object Properties & Methods

Think about your mobile phone. 📱

  • It has things: a brand, a colour, a battery percentage. → These are properties.
  • It can do things: make a call, click a photo, play music. → These are methods.

JavaScript objects work the same way.

MeaningPhone example
PropertyWhat an object has (data)brand, battery
MethodWhat an object can do (a function)call(), charge()

Properties

A property is a key: value pair that stores data about the object.

You learned how to create, read, update, and delete properties in the previous lesson.


Methods

A method is simply a function stored inside an object. You call it with a dot and brackets: object.method().

Two ways to write a method

⚠️ Don't forget the brackets (). calculator.add gives you the function itself, and calculator.add(5, 3) actually runs it.


The this Keyword

Inside a method, this means "the object I belong to."

Think of it like saying "my". When your phone says "my battery is 40%", it means its own battery. 🔋

Real example: a bank account 🏦

⚠️ Don't use arrow functions as methods

Arrow functions don't have their own this, so this won't point to the object.

Rule: For methods that use this, use the short method syntax greet() { }.


Useful Built-in Object Methods

JavaScript gives us ready-made tools in the Object helper.

MethodWhat it does
Object.keys(obj)Gives an array of keys
Object.values(obj)Gives an array of values
Object.entries(obj)Gives an array of key, value pairs
Object.assign(target, source)Copies properties into another object
Object.freeze(obj)Locks the object so it can't be changed

keys, values, entries

Copying and merging objects

If both objects have the same key, the later one wins. That's why theme became "dark".

Freezing an object 🧊

Object.freeze() makes an object immutable by preventing its existing properties from being added, removed, or modified.

Once an object is frozen, its properties cannot be changed directly.

Real-Life Use Case

Imagine a configuration object containing application settings that should never change at runtime.

Here, freezing config prevents accidental changes to important application settings.

Use Object.freeze() for settings that should never change.


Quick Summary Table

TaskCode
Read a propertyobj.name
Write a methodgreet() { return "Hi"; }
Call a methodobj.greet()
Use own data inside a methodthis.name
Get keys / values / pairsObject.keys(), Object.values(), Object.entries()
Merge objects{ ...a, ...b }
Lock an objectObject.freeze(obj)

Key Takeaways

  • Properties are what an object has (data). Methods are what an object can do (functions).
  • Write methods with the short syntax name() { }, and call them with obj.name().
  • Inside a method, this means the object itself, like saying "my".
  • Avoid arrow functions for methods that use this.
  • Use Object.keys(), Object.values(), and Object.entries() to look inside objects, { ...a, ...b } to merge them, and Object.freeze() to lock them.