The object: facts in one place
Section 8: Objects and timeLesson 8.1 · ⏱ 9 min
An object keeps the facts about one thing under names: player.name and player.level. It can hold a function too, and in it this means “this object”.
HTML
<p>Look at the Console 👇</p>
JavaScript
const player = {
name: "Robo",
level: 3,
items: ["key", "map"],
levelUp: function () {
this.level++;
console.log(this.name + " reached level " + this.level);
},
};
console.log(player.name);
console.log(player.items.length);
player.items.push("sword");
console.log(player.items);
player.levelUp();
console.log(JSON.stringify(player));
🖥️ The page in Robo Web:

🖥️ The Console in Robo Web:
Robo
2
["key","map","sword"]
Robo reached level 4
{"name":"Robo","level":4,"items":["key","map","sword"]}pushadds an item to the end of the array.JSON.stringifyturns the whole object into text, and that is how websites save and send their data.
- Add a
coinsproperty, and a functionaddCoins(n)that adds to it and prints it.
📌 Another example: a book card
An object with facts about a book, and we show it on the page.
HTML
<div id="card"></div>
CSS
body { font-family: Tahoma, sans-serif; }
#card { padding: 16px; border-radius: 14px; background: #FFF4C2; font-size: 20px; }
JavaScript
const book = {
title: "A trip to the Moon",
pages: 120,
read: 45,
};
const left = book.pages - book.read;
document.getElementById("card").innerHTML =
"📖 " + book.title + "<br>I read " + book.read + " pages, pages left: " + left;
🖥️ The page in Robo Web:

✍️ Practise
Try the example here: copy the code into its tabs, change it, and watch the page change.
✍️ Practise here in the lesson✖ Close the labor open the lab in a new page ↗
🎯 Challenge yourself
Easy
A car object: print its name and its colour.
👀 Show the solution🙈 Hide the solution
HTML
<p>Console 👇</p>
CSS
body { font-family: Tahoma, sans-serif; }
JavaScript
const car = { name: "Toyota", color: "Red" };
console.log(car.name);
console.log(car.color);
🖥️ The page in Robo Web:

🖥️ The Console in Robo Web:
Toyota Red
Result: Toyota, then Red.
Medium
Change a value in the object and add a new value.
👀 Show the solution🙈 Hide the solution
HTML
<p>Console 👇</p>
CSS
body { font-family: Tahoma, sans-serif; }
JavaScript
const pet = { name: "Mishmish", age: 2 };
pet.age = 3;
pet.type = "cat";
console.log(JSON.stringify(pet));
🖥️ The page in Robo Web:

🖥️ The Console in Robo Web:
{"name":"Mishmish","age":3,"type":"cat"}Result: the age is 3, with a new type.
Hard
An array of objects: print each student's name and mark.
👀 Show the solution🙈 Hide the solution
HTML
<p>Console 👇</p>
CSS
body { font-family: Tahoma, sans-serif; }
JavaScript
const students = [
{ name: "Ali", grade: 90 },
{ name: "Mona", grade: 85 },
];
for (const s of students) {
console.log(s.name + ": " + s.grade);
}
🖥️ The page in Robo Web:

🖥️ The Console in Robo Web:
Ali: 90 Mona: 85
Result: two lines.

