Introduction:
In programming, an object is a collection of data (properties) and methods (functions) that operate on that data.
Key Concepts:
- Key: A unique identifier for a property.
- Value: The data associated with a key.
- Properties: Key-value pairs that store data.
- Methods: Functions that perform actions on the object's data.
Creating an Object:
To create an object in JavaScript, use curly braces ({}):
const person = {
name: "John",
age: 30,
greet: function() { console.log(`Hello, my name is ${this.name}`); }
};
Accessing Properties and Methods:
- To access a property, use the dot (.) notation:
person.name
.
- To invoke a method, use the dot notation followed by parentheses:
person.greet()
.
Unordered Collections of Key-Value Pairs:
Objects can also be used to store unordered collections of key-value pairs:
const fruits = {
apple: "red",
banana: "yellow",
orange: "orange"
};
Key Points:
- Objects represent real-world entities with properties and behaviors.
- Properties are key-value pairs that store data.
- Methods are functions that perform actions on the object's data.
- Objects can also be used as unordered collections of key-value pairs.
- JavaScript objects are enclosed in curly braces ({}) and use the dot notation to access properties and methods.