← Back to course

Objects

Objects

Welcome back.

In the previous lesson, you learned arrays.

Arrays help you store lists of values.

Very useful.

Very powerful.

Very square-bracket friendly.

But sometimes a simple list is not enough.

For example, this is fine:

const user = "Viktor";

But what if we need more information?

Name.

Age.

Email.

Role.

Country.

Favorite programming language.

Level of coffee dependency.

A single string is not enough.

This is where objects enter.

Objects help us store structured data.

Instead of keeping related information in many separate variables, we can keep it inside one object.

Cleaner.

Smarter.

Less chaos.

JavaScript is slowly becoming organized.

Suspiciously organized.

What You Will Learn

In this lesson, you will learn:

By the end of this lesson, you will understand how JavaScript represents real-world things.

Users.

Products.

Courses.

Tasks.

Cars.

Cats.

Even confused developers.

Objects are everywhere in JavaScript.

Everywhere.

Like semicolons in old tutorials.

What Is an Object?

An object is a collection of related data.

Example:

const user = {
  name: "Viktor",
  age: 33,
  role: "Developer"
};

This object has three properties:

name
age
role

Each property has a value:

Viktor
33
Developer

The structure is:

property: value

Objects use curly braces:

{}

Very important.

Arrays use square brackets:

[]

Objects use curly braces:

{}

Different brackets.

Different job.

JavaScript likes brackets.

Maybe too much.

Create the Project

Create a folder for this lesson:

mkdir javascript-lesson6
cd javascript-lesson6
touch index.html
touch script.js

Your project should look like this:

javascript-lesson6/
  index.html
  script.js

Open the folder in your editor.

We will start in the console.

Then we will use objects to update a web page.

No framework dragon today.

Only JavaScript.

Still weird.

But useful.

Write the HTML

Open index.html and add this:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Objects</title>
</head>
<body>
  <h1>Objects</h1>
  <p>Open the browser console to see JavaScript output.</p>

  <script src="script.js"></script>
</body>
</html>

Open the file in your browser.

Open the console:

Now JavaScript is ready.

The console is watching.

Again.

It probably knows too much already.

Your First Object

Open script.js and add:

const course = {
  title: "JavaScript",
  level: "Beginner",
  lessons: 12
};

console.log(course);

Refresh the browser.

You should see the object in the console.

This object represents a course.

It has:

title: "JavaScript"
level: "Beginner"
lessons: 12

One variable.

Many related values.

That is the power of objects.

Instead of three separate variables:

const title = "JavaScript";
const level = "Beginner";
const lessons = 12;

We keep everything together:

const course = {
  title: "JavaScript",
  level: "Beginner",
  lessons: 12
};

Cleaner.

More organized.

Less spaghetti.

More lasagna.

Structured layers.

Very professional.

Very Italian-friendly.

Properties and Values

Objects contain properties and values.

Example:

const user = {
  name: "Anna",
  age: 25,
  isStudent: true
};

Here:

name

is a property.

"Anna"

is the value.

age

is a property.

25

is the value.

isStudent

is a property.

true

is the value.

The pattern is always:

property: value

Use commas between properties:

const product = {
  name: "Laptop",
  price: 900,
  inStock: true
};

No comma after the last property is needed.

But adding one is also common in modern JavaScript:

const product = {
  name: "Laptop",
  price: 900,
  inStock: true,
};

Both are fine.

JavaScript will survive.

Probably.

Accessing Object Properties

You can access object properties using dot notation.

Example:

const user = {
  name: "Viktor",
  age: 33,
  role: "Developer"
};

console.log(user.name);
console.log(user.age);
console.log(user.role);

Output:

Viktor
33
Developer

Dot notation means:

user.name

“Give me the name property from the user object.”

Very readable.

Very common.

Very useful.

Another example:

const product = {
  name: "Keyboard",
  price: 49,
  color: "black"
};

console.log(`Product: ${product.name}`);
console.log(`Price: €${product.price}`);

Output:

Product: Keyboard
Price: €49

Objects help you keep related data together.

Your code becomes easier to understand.

And your future self becomes slightly less angry.

Bracket Notation

There is another way to access properties.

Bracket notation.

Example:

const user = {
  name: "Viktor",
  age: 33
};

console.log(user["name"]);
console.log(user["age"]);

Output:

Viktor
33

This works too.

Dot notation is usually easier:

user.name

Bracket notation is useful when the property name is stored in a variable.

Example:

const propertyName = "name";

console.log(user[propertyName]);

Output:

Viktor

For now, use dot notation most of the time.

It is clean.

It is simple.

It does not look like JavaScript is trying to summon a demon.

Changing Object Values

You can change a property value.

Example:

const user = {
  name: "Anna",
  age: 25
};

user.age = 26;

console.log(user);

Output:

{name: "Anna", age: 26}

The age changed from 25 to 26.

Even if the object was created with const, you can still change its properties.

This is important.

const means you cannot replace the whole object.

But you can change what is inside it.

Example:

const user = {
  name: "Anna",
  age: 25
};

user.age = 26;

This is allowed.

But this is not allowed:

user = {
  name: "Marco",
  age: 30
};

That would try to replace the whole object.

JavaScript will complain.

And honestly, this time JavaScript is right.

Adding New Properties

You can add new properties to an object.

Example:

const user = {
  name: "Viktor",
  age: 33
};

user.role = "Developer";

console.log(user);

Now the object has a new property:

role: "Developer"

Result:

{name: "Viktor", age: 33, role: "Developer"}

This is useful when you receive more information later.

Example:

const product = {
  name: "Mouse",
  price: 25
};

product.inStock = true;

console.log(product);

Objects are flexible.

Sometimes too flexible.

Like a yoga teacher who also knows backend development.

Powerful.

But slightly intimidating.

Deleting Properties

You can delete a property using delete.

Example:

const user = {
  name: "Anna",
  age: 25,
  password: "secret123"
};

delete user.password;

console.log(user);

Output:

{name: "Anna", age: 25}

The password property was removed.

Good.

Never print passwords in real projects.

Never store passwords like this.

Never trust a tutorial password.

This example is only for learning.

Security is not a decorative plant.

It matters.

Objects and Functions

Objects work very well with functions.

Example:

function showUser(user) {
  console.log(`Name: ${user.name}`);
  console.log(`Age: ${user.age}`);
}

const user = {
  name: "Viktor",
  age: 33
};

showUser(user);

Output:

Name: Viktor
Age: 33

The function receives an object.

Then it reads properties from that object.

This is very common in real JavaScript.

Another example:

function createProductMessage(product) {
  return `${product.name} costs €${product.price}.`;
}

const product = {
  name: "Keyboard",
  price: 49
};

console.log(createProductMessage(product));

Output:

Keyboard costs €49.

The object contains data.

The function uses that data.

Clean.

Simple.

Almost suspiciously normal.

Methods

A method is a function inside an object.

Example:

const user = {
  name: "Viktor",
  sayHello: function () {
    console.log("Hello!");
  }
};

user.sayHello();

Output:

Hello!

Here:

sayHello

is a method.

Because it is a function stored inside an object.

You can also use object data inside a method with this.

Example:

const user = {
  name: "Viktor",
  sayHello: function () {
    console.log(`Hello, my name is ${this.name}.`);
  }
};

user.sayHello();

Output:

Hello, my name is Viktor.

this.name means:

“Use the name property from this object.”

this can be confusing.

Very confusing.

For now, remember the basic idea:

Inside an object method, this can refer to the object.

Do not worry if it feels strange.

JavaScript made this strange on purpose.

Probably to keep us humble.

Objects Inside Arrays

Objects and arrays often work together.

Example:

const products = [
  {
    name: "Laptop",
    price: 900
  },
  {
    name: "Mouse",
    price: 25
  },
  {
    name: "Keyboard",
    price: 49
  }
];

console.log(products[0].name);

Output:

Laptop

Here we have an array of objects.

This is extremely common.

Very common.

Almost everywhere common.

A list of users?

Array of objects.

A list of products?

Array of objects.

A list of blog posts?

Array of objects.

Example:

for (const product of products) {
  console.log(`${product.name}: €${product.price}`);
}

Output:

Laptop: €900
Mouse: €25
Keyboard: €49

This is real-world JavaScript.

Data usually comes as lists of objects.

Not always.

But very often.

Get used to this pattern.

It will follow you.

Like browser cache.

Build a Profile Card

Now let us build a small profile card using an object.

Update index.html:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Objects</title>

  <style>
    body {
      font-family: Arial, sans-serif;
      max-width: 700px;
      margin: 60px auto;
      padding: 0 24px;
      background-color: #f3f4f6;
      color: #111827;
    }

    .card {
      background-color: white;
      padding: 24px;
      border: 2px solid #e5e7eb;
      border-radius: 18px;
    }

    h1 {
      font-size: 42px;
    }

    h2 {
      font-size: 30px;
      margin-bottom: 8px;
    }

    p {
      font-size: 20px;
      line-height: 1.6;
    }

    .badge {
      display: inline-block;
      padding: 8px 14px;
      border-radius: 999px;
      background-color: #2563eb;
      color: white;
      font-weight: 700;
    }
  </style>
</head>
<body>
  <h1>Objects</h1>

  <div class="card">
    <h2 id="profileName"></h2>
    <p id="profileRole"></p>
    <p id="profileCountry"></p>
    <span id="profileLevel" class="badge"></span>
  </div>

  <script src="script.js"></script>
</body>
</html>

Now update script.js:

const profile = {
  name: "Viktor",
  role: "JavaScript Student",
  country: "Italy",
  level: "Beginner"
};

const profileNameElement = document.getElementById("profileName");
const profileRoleElement = document.getElementById("profileRole");
const profileCountryElement = document.getElementById("profileCountry");
const profileLevelElement = document.getElementById("profileLevel");

function showProfile(profile) {
  profileNameElement.textContent = profile.name;
  profileRoleElement.textContent = `Role: ${profile.role}`;
  profileCountryElement.textContent = `Country: ${profile.country}`;
  profileLevelElement.textContent = profile.level;
}

showProfile(profile);

Refresh the browser.

You should see a profile card.

JavaScript took data from an object and displayed it on the page.

This is important.

Very important.

Because many websites work like this:

The object is the data.

The DOM is the page.

JavaScript is the waiter carrying information from the kitchen.

Hopefully without dropping the soup.

How This Code Works

This object stores profile data:

const profile = {
  name: "Viktor",
  role: "JavaScript Student",
  country: "Italy",
  level: "Beginner"
};

These lines find HTML elements:

const profileNameElement = document.getElementById("profileName");
const profileRoleElement = document.getElementById("profileRole");
const profileCountryElement = document.getElementById("profileCountry");
const profileLevelElement = document.getElementById("profileLevel");

This function displays the object data:

function showProfile(profile) {
  profileNameElement.textContent = profile.name;
  profileRoleElement.textContent = `Role: ${profile.role}`;
  profileCountryElement.textContent = `Country: ${profile.country}`;
  profileLevelElement.textContent = profile.level;
}

This runs the function:

showProfile(profile);

Notice the pattern:

Data lives in the object.

The function reads the data.

The page shows the data.

This pattern is everywhere.

Simple now.

Powerful later.

Common Mistakes

Forgetting Commas Between Properties

Wrong:

const user = {
  name: "Anna"
  age: 25
};

Correct:

const user = {
  name: "Anna",
  age: 25
};

Use commas between properties.

JavaScript needs them.

It is not good at guessing.

It does not read your soul.

Luckily.

Using = Instead of :

Wrong:

const user = {
  name = "Anna"
};

Correct:

const user = {
  name: "Anna"
};

Inside objects, use : between property and value.

Not =.

Small symbol.

Big difference.

Classic JavaScript trap.

Accessing a Property That Does Not Exist

Example:

const user = {
  name: "Anna"
};

console.log(user.email);

Output:

undefined

There is no email property.

JavaScript returns undefined.

Again.

Very calm.

Very mysterious.

Confusing Arrays and Objects

Array:

const colors = ["red", "green", "blue"];

Object:

const user = {
  name: "Anna",
  age: 25
};

Use arrays for lists.

Use objects for structured details.

A list of names?

Array.

One user with many details?

Object.

A list of users?

Array of objects.

This is the way.

Practice

Create an object named book.

It should have:

Example:

const book = {
  title: "JavaScript Basics",
  author: "InnoMarts",
  pages: 120,
  isFinished: false
};

Print every property in the console:

console.log(book.title);
console.log(book.author);
console.log(book.pages);
console.log(book.isFinished);

Then change isFinished to true.

book.isFinished = true;

Print the object again.

Break it.

Fix it.

That is still the best teacher.

Apart from coffee.

Coffee is also a teacher.

A strict one.

Mini Challenge

Build a small product card.

Create an object:

const product = {
  name: "JavaScript Course",
  price: 49,
  category: "Programming",
  available: true
};

Create HTML with:

Then create a function:

function showProduct(product) {
  // update the page here
}

If available is true, show:

Available now

Otherwise show:

Not available

This is very close to real web development.

Products are objects.

Users are objects.

Orders are objects.

Courses are objects.

Even bugs feel like objects sometimes.

Heavy.

Complicated.

Full of properties you did not ask for.

Summary

Today you learned:

This is a huge step.

Objects are one of the most important parts of JavaScript.

If arrays are lists, objects are details.

Together, they let you model real-world data.

A user.

A product.

A course.

A task.

A message.

A very dramatic banana.

Everything can become an object.

JavaScript is now becoming serious.

Still strange.

But serious.

Next Lesson

In the next lesson, we will learn more about the DOM.

The DOM lets JavaScript talk to the web page.

Change text.

Change styles.

Create elements.

React to users.

Basically, the DOM is where JavaScript stops being theory and starts touching the page.

Carefully.

Usually.