use cases of properties and methods in JavaScript

Properties

Example 1: Basic Object Properties

let calculator = {

add: function(a, b) {

return a + b;

},

multiply: function(a, b) {

return a * b;

}

};

console.log(calculator.add(2, 3)); // Output: 5

console.log(calculator.multiply(4, 5)); // Output: 20

Example 2: Using Dynamic Keys

let property = "color";

let item = {

name: "Chair",

[property]: "blue"

};

console.log(item.color); // Output: blue

Example 3: Nested Properties

let student = {

name: "Alice",

scores: {

math: 85,

science: 92

}

};

console.log(student.scores.math); // Output: 85

Use Cases:

1. Representing Data: Storing attributes like name, age, or preferences.

2. Configuring Settings: For example, settings in an app (e.g., theme: "dark").

---

Methods

Example 1: Object with Methods

let calculator = {

add: function(a, b) {

return a + b;

},

multiply: function(a, b) {

return a * b;

}

};

console.log(calculator.add(2, 3)); // Output: 5

console.log(calculator.multiply(4, 5)); // Output: 20

Example 2: Accessing Properties in Methods

let car = {

brand: "Tesla",

speed: 120,

getDetails: function() {

return `Brand: ${this.brand}, Speed: ${this.speed}`;

}

};

console.log(car.getDetails()); // Output: Brand: Tesla, Speed: 120

Example 3: Chaining Methods

let counter = {

value: 0,

increment: function() {

this.value++;

return this;

},

decrement: function() {

this.value--;

return this;

},

show: function() {

console.log(this.value);

return this;

}

};

counter.increment().increment().decrement().show(); // Output: 1

Use Cases:

1. Encapsulating Behavior: Methods like .start() or .calculate() define actions.

2. Interactive UI: For example, .toggleVisibility() in a component object.

3. APIs: Custom methods like .fetchData() in services.

---

Combining Properties and Methods

Here’s an example where both are used together meaningfully:

let bankAccount = {

accountHolder: "Sarah",

balance: 1000,

deposit: function(amount) {

this.balance += amount;

return `New balance: ${this.balance}`;

},

withdraw: function(amount) {

if (amount > this.balance) {

return "Insufficient funds";

} else {

this.balance -= amount;

return `New balance: ${this.balance}`;

}

}

};

console.log(bankAccount.deposit(500)); // Output: New balance: 1500

console.log(bankAccount.withdraw(200)); // Output: New balance: 1300

---

Key Points to Remember

1. Properties describe the state or attributes of an object.

2. Methods provide the functionality or actions related to the object.

3. Use this in methods

to refer to the object itself.

Get ready to master objects by building and experimenting! Let me know if you'd like challenges or deeper concepts.

Did you find this article valuable?

Support CodeWords by becoming a sponsor. Any amount is appreciated!