02 - JavaScript Objects
02 - JavaScript Objects
Learning Outcomes
1. What is an object?
2. Declaring an object
const person = {
"firstname": "Johnny",
Key-Value pair
"lastname": "Appleseed",
"hobby": "Skydiving",
"employer": "Apple",
"birthday": "Jan 1, 1970",
"children": ["Phillip", "Stacy", "Brian"]
}
key value
Declaring an Object
Keys can be declared with or without double quotes
const person = {
"name":"Peter",
"age":45,
"hasPets":false,
"friends":["Lee", "Michelle", "Emily"],
"employer":{"name":"Apple", "address":"123 Infinity Drive", "city":"Cupertino"}
}
Declaring an Object
An object can have as few or as many properties (key value pairs) as is needed:
const person = {}
What is an Object?
Objects (object literals) are an unordered collection of key-value pairs
Key-Value pair
value
key
Declaring an Object
JavaScript object literals are an unordered collection, which means that the the order of the
key-value pairs do not matter.
const person = {
"name":"Peter",
"age":45,
"hasPets":false
}
console.log(person.name) // outputs "Peter"
const person = {
"name":"Peter",
"age":45,
"hasPets":false
}
person.age = 99 Updated value
const person = {
"name":"Peter",
"age":45,
"hasPets":false
}
delete person.age
console.log(person) // outputs {"name":"Peter", "hasPets":false}
Adding a new Key-Value Pair
To add a new key-value pair, specify the key and its value:
const person = {
"name":"Peter",
"age":45,
"hasPets":false
}
person.favoriteColor = "green"
person.email = "[email protected]"
Does a Key-Value Pair Exist?
Two ways to check if a key-value pair exists:
const person = {
"name":"Peter",
"age":45,
"hasPets":false
}
const people = [
{
"name":"Peter", people[0]
"age":45
},
{
"name":"Mary",
"age":55 people[1]
},
{
"name":"Elliot",
"age":65 people[2]
}
]
Looping Through an Array of Objects
Use a loop to access each item in the array: