Real-life example of object
Imagine you are filling out a form with your personal details, like name, age, and address. Instead of storing each piece of information separately, you can group them together in a single entity—just like an object in JavaScript!
What is Object?
In JavaScript, an object is a collection of key-value pairs enclosed in curly braces {}. A key (also called a 'property name') is usually a string, and its associated value can be of any data type. An object can also be empty, meaning it has no properties.
Creating an Object
const emptyObject={
}
console.log(emptyObject) // {}
const person = {
name: "Prakash",
age: 25,
profession: "Developer"
};
console.log(person); // Output: { name: "Prakash", age: 25, profession: "Developer" }In first example above we have empty Object means no properties
In second example, we have keys (name, age, profession) and values ("Prakash", 25, "Developer")
Accessing Object Properties
Properties can be accessed using dot notation or square brackets:
console.log(person.name); // Output: Prakash (dot notation)
console.log(person["age"]); // Output: 25 (bracket notation)Adding and Modifying Properties
Properties can be added or updated dynamically:
person.city = "New York"; // Adding a new property
person.age = 26; // Modifying an existing property
console.log(person.city); // Output: New York
console.log(person.age); // Output: 26If key is of more than one word, we use square brackets to add
person["Full Name"]="Prakash Kumar" // Adding a new propertyDeleting a Property
You can remove a property using the delete operator:
delete person.profession;
console.log(person); // Output: { name: "Prakash", age: 26, city: "New York" }Note : If key is of more than one word, we can use square brackets [] to add, modify, access and delete
person["Full Name"]="Prakash Kumar" // Adding a new property
console.log(person["Full Name"]) // Accessing a property
person["Full Name"]="Akash Kumar" // Modifying a new property
delete person["Full Name"] // deleting a property
Computed Properties
You can use square brackets to define property names dynamically:
let key = "hobby";
let user = {
[key]: "Reading"
};
console.log(user.hobby); // Output: ReadingProperty Shorthand
The Property Shorthand syntax was introduced in ES6 (ECMAScript 2015). In JavaScript, when creating an object, if the variable names match the object’s property names, you can use a shorthand syntax instead of explicitly writing key-value pairs.
Traditional way of defining properties:let name = "Prakash";
let age = 25;
let person = {
name: name,
age: age
};
console.log(person);
// Output: { name: "Prakash", age: 25 }In the above example, we are repeating the variable names while assigning them as properties of the object. However, JavaScript provides a shorthand notation to simplify this.
Using Property Shorthand:let name = "Prakash";
let age = 25;
let person = { name, age };
console.log(person);
// Output: { name: "Prakash", age: 25 }Here, instead of explicitly specifying name: name and age: age, we use the shorthand notation { name, age }. JavaScript automatically understands that the property name should be the same as the variable name.
- When the variable names are the same as the object’s property names.
- To make the code more concise and readable.
- It is commonly used in ES6+ and modern JavaScript applications.
Nested Objects
Nested objects are objects that contain other objects as property values. This allows you to create complex data structures and organize related information in a hierarchical manner.
Creating Nested Objects:const person = {
name: "Prakash",
age: 25,
address: {
street: "123 Main St",
city: "Mumbai",
country: "India",
postalCode: "400001"
},
contact: {
email: "prakash@example.com",
phone: "+91-9876543210"
}
};
console.log(person);
// Output: {
// name: "Prakash",
// age: 25,
// address: { street: "123 Main St", city: "Mumbai", country: "India", postalCode: "400001" },
// contact: { email: "prakash@example.com", phone: "+91-9876543210" }
// }Accessing Nested Object Properties:// Accessing nested properties using dot notation
console.log(person.address.city); // Output: Mumbai
console.log(person.contact.email); // Output: prakash@example.com
// Accessing nested properties using bracket notation
console.log(person["address"]["city"]); // Output: Mumbai
console.log(person["contact"]["email"]); // Output: prakash@example.com
// Mixed notation
console.log(person.address["postalCode"]); // Output: 400001Modifying Nested Object Properties:// Modifying nested properties
person.address.city = "Delhi";
person.contact.phone = "+91-9876543211";
console.log(person.address.city); // Output: Delhi
console.log(person.contact.phone); // Output: +91-9876543211Adding New Nested Objects:// Adding a new nested object
person.education = {
degree: "Bachelor's in Computer Science",
university: "Mumbai University",
graduationYear: 2020
};
console.log(person.education.degree); // Output: Bachelor's in Computer ScienceDeeply Nested Objects:const company = {
name: "TechCorp",
location: {
address: {
street: "456 Business Ave",
city: "Bangalore",
country: "India",
coordinates: {
latitude: 12.9716,
longitude: 77.5946
}
}
}
};
// Accessing deeply nested properties
console.log(company.location.address.coordinates.latitude); // Output: 12.9716
console.log(company.location.address.coordinates.longitude); // Output: 77.5946Checking for Nested Properties:// Safe way to access nested properties
const user = {
profile: {
name: "John"
}
};
// Unsafe access (will cause error if property doesn't exist)
// console.log(user.profile.address.city); // Error: Cannot read property 'city' of undefined
// Safe access using optional chaining (ES2020)
console.log(user.profile?.address?.city); // Output: undefined (no error)
// Traditional safe access
if (user.profile && user.profile.address) {
console.log(user.profile.address.city);
} else {
console.log("Address not available");
}Practical Example - E-commerce Product:const product = {
id: "P001",
name: "Smartphone",
price: 25000,
category: "Electronics",
specifications: {
brand: "TechBrand",
model: "X1",
color: "Black",
storage: "128GB",
ram: "8GB"
},
seller: {
name: "TechStore",
rating: 4.5,
location: {
city: "Mumbai",
state: "Maharashtra"
}
},
reviews: [
{ user: "User1", rating: 5, comment: "Great product!" },
{ user: "User2", rating: 4, comment: "Good value for money" }
]
};
// Accessing product details
console.log(product.name); // Output: Smartphone
console.log(product.specifications.brand); // Output: TechBrand
console.log(product.seller.location.city); // Output: Mumbai
console.log(product.reviews[0].comment); // Output: Great product!Object Methods
In JavaScript, methods are functions that belong to an object. These methods can perform operations using the object's properties and can be invoked using dot notation.
Defining Methods in ObjectsMethods are typically defined using either the traditional function syntax or the ES6 shorthand method syntax. Let’s look at an example:
const person = {
name: "Prakash",
// Traditional function syntax
sayHello: function() {
console.log("Hello, " + this.name);
},
// ES6 shorthand method syntax
greet() {
console.log("Hi, " + this.name);
}
};
// Calling object methods
person.sayHello(); // Output: Hello, Prakash
person.greet(); // Output: Hi, PrakashObject.keys() and Object.values()
JavaScript provides several built-in methods for working with objects. Two of the most commonly used methods are Object.keys() and Object.values().
The Object.keys() method returns an array of all the keys (property names) of an object.
const person = {
name: "Prakash",
age: 25,
profession: "Developer",
city: "Mumbai"
};
// Get all keys from the object
const keys = Object.keys(person);
console.log(keys); // Output: ["name", "age", "profession", "city"]
// Iterating over object keys
keys.forEach(key => {
console.log(`Key: ${key}, Value: ${person[key]}`);
});
// Output:
// Key: name, Value: Prakash
// Key: age, Value: 25
// Key: profession, Value: Developer
// Key: city, Value: MumbaiObject.values():The Object.values() method returns an array of all the values present in an object.
// Get all values from the object
const values = Object.values(person);
console.log(values); // Output: ["Prakash", 25, "Developer", "Mumbai"]
// Calculate sum of numeric values
const numbers = Object.values(person).filter(value => typeof value === 'number');
const sum = numbers.reduce((acc, val) => acc + val, 0);
console.log(sum); // Output: 25 (only age is a number)
// Check if object has specific values
const hasDeveloper = Object.values(person).includes("Developer");
console.log(hasDeveloper); // Output: truePractical Examples:// Example 1: Form validation
const formData = {
username: "prakash123",
email: "prakash@example.com",
password: "secure123",
confirmPassword: "secure123"
};
// Check if all fields are filled
const isEmpty = Object.values(formData).some(value => !value);
console.log("Form has empty fields:", isEmpty); // Output: false
// Example 2: Shopping cart
const cart = {
laptop: 45000,
mouse: 1200,
keyboard: 2500,
headphones: 3500
};
// Calculate total price
const total = Object.values(cart).reduce((sum, price) => sum + price, 0);
console.log("Total cart value:", total); // Output: 52200
// Get product names (keys)
const products = Object.keys(cart);
console.log("Products in cart:", products); // Output: ["laptop", "mouse", "keyboard", "headphones"]
// Example 3: User permissions
const userPermissions = {
read: true,
write: false,
delete: false,
admin: true
};
// Get all permissions that are true
const activePermissions = Object.keys(userPermissions).filter(
permission => userPermissions[permission] === true
);
console.log("Active permissions:", activePermissions); // Output: ["read", "admin"]Combining Object.keys() and Object.values():const student = {
name: "Prakash",
age: 20,
grade: "A",
subjects: ["Math", "Science", "English"]
};
// Get both keys and values
const keys = Object.keys(student);
const values = Object.values(student);
console.log("Keys:", keys);
// Output: ["name", "age", "grade", "subjects"]
console.log("Values:", values);
// Output: ["Prakash", 20, "A", ["Math", "Science", "English"]]
// Create a formatted string
const studentInfo = keys.map((key, index) =>
`${key}: ${values[index]}`
).join(", ");
console.log(studentInfo);
// Output: "name: Prakash, age: 20, grade: A, subjects: Math,Science,English"Use Cases:- Object.keys(): Useful for iterating over object properties, form validation, and dynamic property access.
- Object.values(): Useful for calculations, filtering, and working with just the values without their keys.
- Both methods: Essential for modern JavaScript development and functional programming patterns.
Summary
- Objects store data as key-value pairs.
- Properties can be accessed, modified, added, or deleted dynamically.
- Dot notation and square brackets are used for property access.
- Computed properties allow dynamic keys.
- Property shorthand notation makes object creation more concise.
- Nested objects allow creating complex data structures with hierarchical organization.
- Objects can have methods to perform actions.
- Object.keys() returns an array of all property names in an object.
- Object.values() returns an array of all values in an object.
- Both Object.keys() and Object.values() are essential for modern JavaScript development.