Objects
Objects in JavaScript are
collections of key-value pairs. Keys (also called properties) are usually
strings, and values can be any data type.
javascript
// Example of
an object
const person =
{
name:
"John", // Key: "name", Value: "John"
(String)
age:
30, // Key: "age", Value: 30 (Number)
isEmployed:
true, // Key: "isEmployed", Value: true (Boolean)
};
console.log(person);
// Logs the entire object: { name: "John", age: 30, isEmployed: true }
Explanation:
·
Keys define the "labels" for the data.
·
Values are the actual data associated with those keys.
·
Access properties using dot
notation (e.g., person.name) or bracket notation (e.g., person["name"]).
2. Adding and Updating Properties
You can add new properties or
update existing ones using dot or bracket notation.
javascript
const person =
{ name: "John", age: 30 };
// Adding a
new property
person.gender
= "Male"; // Dot notation
console.log(person);
// { name: "John", age: 30, gender: "Male" }
// Updating an
existing property
person.age =
31;
console.log(person.age);
// Output: 31
// Using
bracket notation
person["country"]
= "USA"; // Adding new property
console.log(person);
// { name: "John", age: 31, gender: "Male", country:
"USA" }
Notes:
·
Use dot notation for simplicity when the property name is valid.
·
Use bracket notation when the property name includes spaces or
special characters (e.g., person["first
name"]).
3. Deleting Properties
To remove a property from an
object, use the delete operator.
javascript
const person =
{ name: "John", age: 30, gender: "Male" };
// Deleting
the "gender" property
delete
person.gender;
console.log(person);
// { name: "John", age: 30 }
Notes:
·
Deleting removes the key-value pair completely from the object.
4. Object Methods
Objects can contain functions as
properties, which are called methods.
javascript
const car = {
brand:
"Tesla",
start:
function () {
console.log("Car
started");
},
};
// Calling the
method
car.start();
// Output: "Car started"
Explanation:
·
Methods allow objects to perform actions.
·
Use the this keyword inside methods to refer to the object itself.
5. Iterating Over Objects
You can loop through an object's
properties using for...in or Object methods.
javascript
const car = {
brand: "Tesla", color: "Red", year: 2022 };
// Using
for...in
for (let key
in car) {
console.log(`${key}:
${car[key]}`);
}
// Output:
// brand: Tesla
// color: Red
// year: 2022
// Using
Object methods
console.log(Object.keys(car));
// ["brand", "color", "year"]
console.log(Object.values(car));
// ["Tesla", "Red", 2022]
console.log(Object.entries(car));
// [["brand", "Tesla"], ["color",
"Red"], ["year", 2022"]]
Notes:
·
Object.keys() returns an
array of property names.
·
Object.values() returns an
array of property values.
·
Object.entries() returns an
array of key-value pairs.
6. Checking Properties
Use the in operator
or hasOwnProperty to check if a property exists.
javascript
const car = {
brand: "Tesla", color: "Red" };
// Using the "in"
operator
console.log("brand"
in car); // true
console.log("year"
in car); // false
// Using
hasOwnProperty
console.log(car.hasOwnProperty("color"));
// true
console.log(car.hasOwnProperty("model"));
// false
Notes:
·
in checks for
inherited properties too.
·
hasOwnProperty checks
only the object's own properties.
7. Object Destructuring
Destructuring allows you to extract
specific properties into variables.
javascript
const person =
{ name: "John", age: 30, gender: "Male" };
//
Destructuring properties
const { name,
age } = person;
console.log(name);
// Output: "John"
console.log(age);
// Output: 30
// Renaming
variables
const {
gender: personGender } = person;
console.log(personGender);
// Output: "Male"
Notes:
·
Destructuring simplifies property extraction and improves readability.
8. Spread and Rest Operators
The spread operator ... copies or
combines objects. The rest operator ... collects remaining properties.
javascript
const car = {
brand: "Tesla", color: "Red" };
// Spread
operator: Copying an object
const newCar =
{ ...car, year: 2022 };
console.log(newCar);
// { brand: "Tesla", color: "Red", year: 2022 }
// Rest
operator: Collecting remaining properties
const { brand,
...others } = newCar;
console.log(brand);
// Output: "Tesla"
console.log(others);
// { color: "Red", year: 2022 }
Notes:
·
Spread is useful for immutability (avoiding changes to the
original object).
·
Rest is handy for separating specific properties from the rest.
9. Freezing and Sealing Objects
·
Object.freeze() prevents
any modifications (add, delete, or update).
·
Object.seal() allows
updates but prevents adding or removing properties.
javascript
const person =
{ name: "John", age: 30 };
Object.freeze(person);
person.age =
31; // No effect
console.log(person);
// { name: "John", age: 30 }
const car = {
brand: "Tesla", color: "Red" };
Object.seal(car);
car.color =
"Blue"; // Allowed
delete
car.brand; // Not allowed
console.log(car);
// { brand: "Tesla", color: "Blue" }
Notes:
·
Use freezing for strict immutability.
·
Use sealing when you only want to allow updates.
10. Prototype and Inheritance
Objects can inherit properties from
another object (prototype).
javascript
const animal =
{ species: "Dog" };
const pet =
Object.create(animal); // pet inherits from animal
pet.name =
"Buddy";
console.log(pet.name);
// Output: "Buddy"
console.log(pet.species);
// Output: "Dog" (inherited from animal)
Notes:
·
Object.create() creates a
new object with the specified prototype.
·
Use prototypes to share properties or methods across multiple
objects.
11. JSON (JavaScript Object
Notation)
JSON is a lightweight format for
exchanging data.
javascript
const person =
{ name: "John", age: 30 };
// Converting
object to JSON string
const
jsonString = JSON.stringify(person);
console.log(jsonString);
// '{"name":"John","age":30}'
// Parsing
JSON string back to an object
const
parsedObject = JSON.parse(jsonString);
console.log(parsedObject);
// { name: "John", age: 30 }
Notes:
·
JSON is widely used for APIs and data storage.
·
Only simple data types are supported (no methods).