𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗢𝗯𝗷𝗲𝗰𝘁𝘀
JavaScript objects store values and functions.
Think about a car. All cars have properties like color and model. All cars have methods like drive or brake. The values and timing change for every car.
Properties and Methods
- Properties store data as key-value pairs.
- Methods store functions as values.
Example of an object:
const car = { type: "Fiat", model: "500", color: "white" };
In this example, type, model, and color are properties. "Fiat", "500", and "white" are the values.
Creating Objects
You use object literals to define objects. You put key-value pairs inside curly braces. You do not need specific spacing or line breaks.
Example:
const person = { firstName: "John", lastName: "Doe", age: 50, eyeColor: "blue" };
Managing Properties
You can change, add, or delete properties at any time.
How to access properties:
Dot notation: person.age This is the best way for readability.
Bracket notation: person["age"] Use this if your property name is in a variable or contains special characters like hyphens.
Expression: person[x]
Object Methods
Methods are actions objects perform. A method is a function stored inside an object property.
Example:
const person = { firstName: "John", lastName: "Doe", fullName: function() { return this.firstName + " " + this.lastName; } };
Source: https://www.w3schools.com/js/js_object_methods.asp Full post: https://dev.to/madhanraj/javascript-objects-4i67