JavaScript Objects
JavaScript objects are used to store related information together using key-value pairs.
What is a JavaScript Object?
A JavaScript object is a collection of related data stored using key-value pairs.
Each key describes a piece of information and the value stores the actual data associated with that key.
Why Do We Use Objects?
Objects help us keep related information together instead of storing every value in a separate variable.
For example, a student can have a name, age, course, and city inside one object.
JavaScript Object - Key-Value Structure and Object Properties
Object Structure
An object is written using curly braces { }. Inside the braces, properties are written as key-value pairs.
let student = {
name: "Amit",
age: 22,
course: "JavaScript"
};
How JavaScript Objects Store Data
Each property contains a key and its corresponding value inside the JavaScript object.
Common Object Properties
Name Property
Stores the name or title related to the object.
Age Property
Stores a numeric value such as a person's age.
Course Property
Stores information about a course or subject.
City Property
Stores location-related information.
Example 1: Creating an Object
We can create an object using curly braces and define its properties using key-value pairs.
let student = {
name: "Amit",
age: 22,
course: "JavaScript"
};
console.log(student);
Example 2: Accessing Object Properties
We can access an object's property using dot notation.
let student = {
name: "Amit",
course: "JavaScript"
};
console.log(student.name);
console.log(student.course);
Amit
JavaScript
Example 3: Updating an Object Property
Existing property values can be changed by assigning a new value to the property.
let student = {
name: "Amit",
age: 22
};
student.age = 23;
console.log(student.age);
Example 4: Adding a New Property
A new property can be added to an existing object by assigning a value to a new property name.
let student = {
name: "Amit",
course: "JavaScript"
};
student.city = "Pune";
console.log(student.city);
Summary
JavaScript objects are used to store related information using key-value pairs. Objects can contain multiple properties, and we can create, access, update, and add properties as required.