Objects
Programs often need to keep related pieces of data together.
For example, a pet can have a name, a type, and an age. Instead of creating separate variables for each detail, JavaScript lets you group them in one object.
What an object is
An object stores related information in one variable.
In JavaScript, objects use curly braces {}.
Each piece of information inside an object has a name and a value.
Key-value pairs
Object data is written as key-value pairs.
- A key is the name of a piece of data, like
nameorage. - A value is the actual data, like
"Bella"or3.
A colon : connects the key and value.
Commas , separate multiple key-value pairs.
First code example
Here is a simple pet object.
const pet = {
name: "Bella",
type: "dog",
age: 3
};
console.log(pet);Code walkthrough
Let's break down what happens in the code above:
const petcreates a variable namedpet.- The curly braces
{}create an object. - The object has three key-value pairs:
name: "Bella",type: "dog", andage: 3. - The commas separate the key-value pairs.
console.log(pet)sends the full object to the Output section after you click Run.
Reading one value from an object
Often, you do not need the whole object at once. You may only want one specific value.
You can read one value with dot notation.
To use dot notation, write the object name, a dot ., and the key you want to read.
const userProfile = {
username: "coder123",
level: 5
};
console.log(userProfile.username);This sends "coder123" to the Output section because username is the value we asked for.
You may also see bracket notation, like userProfile["username"]. For this lesson, dot notation is the simplest option.
Mini task
Look at the userProfile code block above.
Change console.log(userProfile.username) so it prints the user's level instead.
Short quiz
Question 1: What symbols are used to create an object?
Answer: Curly braces {}.
Question 2: What punctuation mark separates multiple key-value pairs?
Answer: A comma ,.
Small challenge
Create an object called course that represents this lesson.
Give it a title key with a string value, like "JavaScript".
Give it a duration key with a number value, like 4.
Use dot notation inside console.log() to print the title of the course.
// put your code below
console.log()Summary
- An object stores related information in one variable.
- Objects use curly braces
{}. - Object data is written as key-value pairs.
- A key is the label, and a value is the data itself.
- Commas separate multiple key-value pairs.
- Dot notation reads one value from an object, like
person.name.