Objects
Objects are collections of key–value
pairs, where keys (also called properties) are strings (or Symbols) and values
can be any data type, including other objects and functions. They are used to
represent real-world entities in code.
Object
Literals
The simplest way to create an object
is by using object literal syntax.
let
person = {
name: "John",
age: 30,
isEmployed: true
};
console.log(person);
// {name: "John", age: 30, isEmployed: true}
Properties
and Methods
- Properties
are values stored in the object.
- Methods
are functions defined inside an object.
let
car = {
brand: "Toyota",
model: "Corolla",
year: 2022,
start: function() {
console.log("Car started!");
}
};
console.log(car.brand);
// Toyota
car.start();
// Car started!
this Keyword
Inside an object method, this refers to the object itself.
let
user = {
name: "Alice",
greet: function() {
console.log("Hello, my name is "
+ this.name);
}
};
user.greet();
// Hello, my name is Alice
Accessing
and Updating Properties
You can access object properties in
two ways: dot notation and bracket notation.
let
book = { title: "1984", author: "George Orwell" };
//
Dot notation
console.log(book.title);
// 1984
//
Bracket notation
console.log(book["author"]);
// George Orwell
//
Updating property
book.title
= "Animal Farm";
console.log(book.title);
// Animal Farm
//
Adding a new property
book.year
= 1945;
console.log(book.year);
// 1945
Nested
Objects
Objects can contain other objects as
values.
let
student = {
name: "Emma",
grades: {
math: 90,
science: 85
}
};
console.log(student.grades.math);
// 90
//
Updating nested property
student.grades.science
= 95;
console.log(student.grades.science);
// 95