Objects
An object is an collection value and key pair.
Creating Objects
- we use curley brackets {} or object literal to create object.
ex-
let user = { name: "John", age: 18 isAdult: true }
Different Operations perform in objects
- Accessing a value
- Adding a new property
- Updating a value
- Deleting the property
Accessing a value
For accessing value from an object.
we use 2 operator
- Dot Operator
- Sqaure brakcet operator
Dot Operator( . )
The dot Operator does only one things is to access the value
ex-
let user = {
name: "John",
age: 18
isAdult: true
}
user.name
"John"
Square brackets( [] )
The square brackets does two things computes the value and access it
when to use square brackets??
- when there is space
- other symbol or number
- or it is stored in a varibale we use it
ex
let user = {
name: "John",
age: 18
isAdult: true
}
user[name]
"John"
Adding a new property
To Add new property
- name of the object follwed by dot ( . ) operator
- name of the key
ex-
- Using dot operator
user.city = "London"
"London
- Using sqaure bracket
user["batch"] = 8
"batch"
if we access user
user
age: 18
city: "london"
name: "John"
isAdult: true
Updating a value
- When the key doesn`t exist it create new property
- if key exist it will update the property
ex-
user.age = 26
<. 26
if we access the user
user:
age: 26 (age is update from 18 to 24)
city: "London"
batch: 8
is Adult: true
name: "John"
Deleting a Key
- delete is speacial keyword to delete a property of an object.
- delete followed by name of object and key want to delete
ex-
delete use.city
<. true
user
age: 26 (age is update from 18 to 24)
batch: 8
is Adult: true
name: "John"
city key and value is deleted
Rules for naming the key in an object
- when key is an single word don`t put in double quote
- whenever you have multiple word keyname remeber to put in double quotes( " " )
- if you don`t put in double quotes( " " ) it shoes an error.