Why do we use objects in JS?
We use objects in JavaScript because they allow us to group related data and functionalities together into a single, organized structure using key-value pairs.
Without Objects (Messy & Hard to Manage)
With Objects (Clean & Organized)
In Javascript Objects are king,If we undersatnd Objects meant understand Javascript.
Object structure:
An object literal is a list of property key:values inside curly braces
{ }.
Example:
const car = {
type: "Fiat",
model: "500",
color: "white"
};
Create a new JavaScript object using new Object():
Example:
const person = new Object({
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
});
In objects Properties can be changed, added, and deleted.
Example:
const car = {
type: "Fiat",
model: "500",
color: "white"
};
Accessing property value,
You can access object properties in these ways:
- Dot notation
- Bracket notation
- Expression
console.log(car.type);//output:Fiat
console.log(car["type"]);//output:Fiat
*Output:Fiat *
To change value,
car.type="Masda";
console.log(car.type)
Output:Masda
Adding new Property
car.year=2000;
Output:
{type: 'Fiat', model: '500', color: 'white', year: 2000}
Deleting property
delete car.color;
console.log(car);
{type: 'Fiat', model: '500', year: 2000}
Check if a Property Exists:
Use the in operator to check if a property exists in an object:return boolean value
const person = {
firstName: "Karthika",
lastName: "Jasinska"
};
let result = ("firstName" in person);
console.log(result)
Output:
true
Top comments (0)