Unit 2 home
FSWD · MERN CLASS 15 / 48 60-MIN SESSION OBJECTS
UNIT 2 · JAVASCRIPT (ES6) PART G · CLASS 3 OF 8 UI23PC510CS · THEORY

Class 15 — many facts, one tidy container

One dish isn't one fact. It's a name, a price, a category, a yes/no — all at once. Today you keep them together.

In Class 14 a variable held one value — let price = 90;. But describe a real menu dish and you instantly need several facts that belong together: its name, its price, its category, whether it's a millet dish. Keeping them in four loose variables (dishName, dishPrice, dishCategory…) gets messy fast and nothing says they're related. JavaScript's answer is the object: one container that holds many labelled values as a single unit. Today you'll build one, read from it two ways, give it a method, and nest one object inside another.

Walk out of this room able to…

Explain why objects exist — group related values into one container instead of loose variables
Write an object literal — { key: value } — and read it with dot and bracket notation (exam: P2·Q4)
Add a method to an object (a function stored as a value) and use this at its simplest
Nest an object inside an object, and know when to reach for an object vs an array
TODAY, POINT BY POINT
01Why objects exist — four loose variables vs one tidy containerIDEA
02Object literal syntax — { key: value }, one dish modelled as one objectBUILD
03Accessing properties — dot notation vs bracket notationBUILD
04Exam — add a property with dot and bracket notation (P2·Q4·2m)PYQ
05Activity — build an object from a written specTRY IT
06Objects with methods — a function stored as a property; this, at minimum depthBUILD
07Activity — predict the output of an object + console.logTRY IT
08Nested objects — an object holding a sub-object (nutrition)IDEA
09Object vs array — a quick-decision reference (self-study)READ
10Take-home kit — the object cheat-card and the bridge to Class 16 (the DOM)WRAP
NOTHING TO DOWNLOAD TODAY — ZERO ASSETS

Every demo runs live, right on this slide. To practise on your own machine, make a fresh throwaway folder fswd-practice\Class-15\, open it in VS Code, and create a scratch script.js there — build tiny files from scratch, run them, throw them away. Nothing here is committed: fswd-practice\ is scratch paper, never a git repo. The real poshtik-campus\ project — and its commits — live only in the lab classes. Never here.

To see any output on your own machine: open your .html file in the browser, then press F12 (or right-click → Inspect) and click the Console tab — that's where every console.log appears.

"Which .html file?" — the two-file pair, restated in 8 lines

Every panel today is captioned script.js, and a .js file can't run by itself — a page has to load it. You built this exact page in Class 13 and again in Class 14, so we won't labour it; here it is once, complete, so nothing today is a mystery. Objects live entirely in the Console — they have no appearance on a page — so this host page stays deliberately bare. It exists only to start script.js.

practice.html · complete file, from scratchBUILDS ONE PRESS AT A TIME
1<!DOCTYPE html>
2<html lang="en">
3<head>
4 <title>Class 15 — objects</title>
5</head>
6<body>
7 <script src="script.js"></script> <!-- the only line that matters -->
8</body>
9</html>
·9 lines, no CSS at all today — an object has no colour, no size, no position. Nothing to style. Save this beside your script.js in the SAME folder.
file:///C:/Users/student/Desktop/fswd-practice/Class-15/practice.html

(a blank white page — and that is the correct result)

✓ Nothing on screen, by design. Press F12 → Console and today's objects are all there. Class 16 is where JavaScript finally starts changing what the visitor sees.

Why no CSS today — and why that's a real answer, not a shortcut. A stylesheet decides how elements look. An object is pure data sitting in memory; it never appears on the page, so there is genuinely nothing for CSS to style. This is also the honest reason today's page is 9 lines instead of Unit 1's rich markup: we build only the HTML the concept actually needs. Tomorrow, in Class 16, objects meet the page — and CSS comes straight back.

"But how do I see an object without HTML and CSS?" — the honest answer, both ways

Fair question, and it deserves a real demonstration rather than a promise. A pure-JS lesson has two legitimate output surfaces, and you should know both: (1) the Console — which is what today uses, and it is a genuine output screen, not a placeholder; and (2) a page, once you decide to show the data to a visitor. Below is the same dish object rendered the second way, so the difference is concrete. Note the order — plain HTML first, then CSS, then the JavaScript that fills it in.

show-dish.html + style.css + script.js · plain HTML → CSS → JSHTML BUILDS, THEN CSS, THEN JS
1<body>
2 <h2 id="dish-name"></h2> <!-- empty holders -->
3 <p id="dish-price"></p>
4 <script src="script.js"></script>
5</body>
·/* Plain HTML above: two empty placeholders. Now style.css ↓ */
6 #dish-name { color: seagreen; }
7 #dish-price { font-weight: bold; }
·/* Styled, but still showing "—". Now script.js pours the OBJECT in ↓ */
8const dish = { name: "Millet Khichdi", price: 90 };
9document.getElementById("dish-name").textContent = dish.name;
10document.getElementById("dish-price").textContent = "₹" + dish.price;
·THE WHOLE PROGRESSION IN ONE PANEL: HTML makes the holders, CSS gives them a look, JS fills them from the object. Class 16 teaches lines 9-10 properly.
REAL OUTPUT — HTML, THEN CSS, THEN THE OBJECT'S DATA
file:///C:/Users/student/Desktop/fswd-practice/Class-15/show-dish.html

Millet Khichdi

₹90

↑ PLAIN HTML — EMPTY HOLDERS, DEFAULT BLACK, NO CSS AND NO JS YET

Three distinct phases in one preview: bare dashes → the dashes get colour and weight → the object's real values replace them. That is what "visualising an object" means once you leave the Console.

So both answers are true: a pure-JS lesson visualises through the Console (a real output surface — today's panels), and the moment you want a visitor to see the data, you add the smallest HTML + CSS that the data needs and let JS fill it. Class 16 is that class, in full.

The rule this class follows, stated plainly: HTML/CSS is built only to the level the concept needs — no more. For objects, that level is nearly zero, so the Console is the honest output screen. For the DOM (Class 16), the level is a real page, so a real page gets built. Either way the order never changes: plain HTML → CSS → JavaScript.

The idea, in one plain sentence

One real thing has many facts that belong together. An object keeps them in one container.

Think of a single dish on the Poshtik Campus menu — say Millet Khichdi. It isn't one fact. It has a name, a price, a category, and a yes/no flag for "is it a millet dish?". In Class 14 each of those would be its own loose variable. That works for one dish… but the four boxes just float around with nothing tying them together. JavaScript's answer is the object: one box that holds many labelled values as a single unit.

The messy way vs the tidy way — same four facts, side by side

First the loose-variable approach you already know — and because JavaScript can never run on its own, we build its host page from scratch first too: plain HTML → CSS → JS. Step through it: four separate boxes, and the only thing linking them is that you remembered to start each name with dish. In the next beat the same four facts get poured into one object.

loose.html + style rules + script.js · four loose variables (the old way), plain HTML → CSS → JSHTML, THEN CSS, THEN JS — ONE PRESS PER LINE
·<!-- FILE 1 of 3 · loose.html — the page that will CARRY script.js -->
1<!DOCTYPE html>
2<html lang="en">
3<head>
4 <meta charset="UTF-8">
5 <title>Four loose variables</title>
6</head>
7<body>
8 <h1>The messy way</h1>
9 <p class="tip">Four unlinked boxes — check the Console (F12).</p>
10</body>
11</html>
·/* HTML complete & PLAIN above. FILE 2 of 3 · the CSS — one rule per press ↓ */
6 <style>
7 body { font-family: Georgia, serif; padding: 18px; }
8 h1 { color: #B91C1C; font-size: 20px; }
9 .tip { color: #64748B; font-size: 13px; }
10 </style>
·<!-- CSS done. Hire the passenger — last line before </body> -->
11 <script src="script.js"></script>
·// ————— FILE 3 of 3 · script.js — four separate, unlinked boxes —————
1// one dish = four separate, unlinked boxes
2let dishName = "Millet Khichdi";
3let dishPrice = 90;
4let dishCategory = "bowl";
5let dishIsMillet = true;
6console.log(dishName);
7console.log(dishPrice);
·nothing in the code says these four boxes describe the SAME dish. Add a second dish and you'd need dish2Name, dish2Price… it gets messy fast
REAL OUTPUT — PLAIN PAGE, THEN CSS, THEN THE TWO PRINTS
file:///C:/Users/student/Desktop/fswd-practice/Class-15/loose.html

The messy way

Four unlinked boxes — check the Console (F12).

PLAIN HTML — NO CSS AND NO SCRIPT YET
DEVTOOLS · CONSOLE — THE REAL OUTPUT
Millet Khichdiconsole.log(dishName)
90console.log(dishPrice)
The data is all there — but it took four unrelated boxes to describe one dish, and the page itself had to be built to run them. Next beat: the same facts in one object.

Now the same dish as one object — page and all, built from scratch

Same fixed order as always: plain HTML first (the page that will carry the script), then CSS one rule per press, then the JavaScript. Watch three things on the right: the white page appears plain, then each CSS rule lands, then the dark Console shows the object growing one property at a time and printing as a single tidy unit.

dish.html + style rules + script.js · plain HTML → CSS → JSHTML, THEN CSS, THEN JS — ONE PRESS PER LINE
·<!-- FILE 1 of 3 · dish.html — the page that will CARRY script.js -->
1<!DOCTYPE html>
2<html lang="en">
3<head>
4 <meta charset="UTF-8">
5 <title>One dish, one object</title>
6</head>
7<body>
8 <h1>Poshtik Campus</h1>
9 <p class="tip">The dish object prints in the Console (F12).</p>
10</body>
11</html>
·/* HTML complete & PLAIN above. FILE 2 of 3 · the CSS — one rule per press ↓ */
6 <style> /* typed back up in the <head> */
7 body { font-family: Georgia, serif; padding: 18px; }
8 h1 { color: seagreen; font-size: 20px; }
9 .tip { color: #64748B; font-size: 13px; }
10 </style>
·<!-- CSS done. Hire the passenger — last line before </body> -->
11 <script src="script.js"></script>
·// ————— FILE 3 of 3 · script.js — one object, four labelled facts —————
1// one dish = ONE object holding four labelled facts
2const dish = {
3 name: "Millet Khichdi",
4 price: 90,
5 category: "bowl",
6 isMillet: true
7};
8console.log(dish);
·ONE name — dish — now carries all four facts together. They can never drift apart again
REAL OUTPUT — PLAIN PAGE, THEN CSS, THEN THE OBJECT GROWS
file:///C:/Users/student/Desktop/fswd-practice/Class-15/dish.html

Poshtik Campus

The dish object prints in the Console (F12).

PLAIN HTML — NO CSS AND NO SCRIPT YET
DEVTOOLS · CONSOLE — THE OBJECT GROWS
// dish opened
{ name: 'Millet Khichdi' }
{ name: 'Millet Khichdi', price: 90 }
{ name: 'Millet Khichdi', price: 90, category: 'bowl' }
{ name: 'Millet Khichdi', price: 90, category: 'bowl', isMillet: true }
// object closed
› { name: 'Millet Khichdi', price: 90, category: 'bowl', isMillet: true }
Two surfaces, as always. The white area is what a visitor sees — HTML built it, CSS dressed it. The object never appears there, because an object is data, not markup: it prints to the Console. In Class 16 you'll learn the one line that puts dish.name onto the visible page.
EXTRA DEPTH · FOR SELF-PACED READERS

Each labelled value inside the braces is called a property — a key (the label, e.g. name) paired with a value (e.g. "Millet Khichdi"). An object is simply a bundle of key–value pairs. We used const dish because the box itself won't be re-pointed to a different object — even though, as you'll see later, the values inside it can still change.

The shape, exactly

The object literal — { key: value }, pairs separated by commas.

"Literal" just means you write the object out in full, right there in the code, between curly braces. Learn these five rules once and you can read or write any object: (1) wrap everything in curly braces { }; (2) each entry is a key, then a colon, then a value; (3) separate entries with commas; (4) keys are labels (usually plain words, no quotes needed); (5) values can be any type you already know — string, number, boolean.

PieceWhat it isIn our dish object
{ }the object's outer wrapperholds all the dish's facts as one unit
keythe label for one factname, price, category, isMillet
:the colon — "this key holds this value"name: "Millet Khichdi"
valuethe actual data (any type)"Millet Khichdi", 90, true
,the comma — separates pairsafter every pair except (optionally) the last

Build one dish object, one line per press — page included, from scratch

Same unbreakable order: plain HTML → CSS → JavaScript. First the page that carries the script (plain, then three CSS rules land one press at a time), then the object literal itself. As the object closes, the Console prints the finished dish — proof the braces built a real value. Notice the keys stay fixed while the values are the three data types from Class 14: a string, a number, a boolean.

literal.html + style rules + script.js · plain HTML → CSS → JSHTML, THEN CSS, THEN JS — ONE PRESS PER LINE
·<!-- FILE 1 of 3 · literal.html — plain HTML, nothing styled yet -->
1<!DOCTYPE html>
2<html lang="en">
3<head>
4 <meta charset="UTF-8">
5 <title>Object literal</title>
6</head>
7<body>
8 <h1>Object literal syntax</h1>
9 <p class="tip">Open the Console (F12) to watch the object build.</p>
10</body>
11</html>
·/* HTML complete & PLAIN above. FILE 2 of 3 · the CSS — one rule per press ↓ */
6 <style>
7 body { font-family: Georgia, serif; padding: 18px; }
8 h1 { color: #7C3AED; font-size: 20px; }
9 .tip { color: #64748B; font-size: 13px; }
10 </style>
·<!-- CSS done. Hire the passenger — last line before </body> -->
11 <script src="script.js"></script>
·// ————— FILE 3 of 3 · script.js — one dish, as an object literal —————
1const dish = { // open the object
2 name: "Millet Khichdi", // string value
3 price: 90, // number value
4 category: "bowl", // string value
5 isMillet: true // boolean — no comma, it's last
6}; // close the object
7console.log(dish);
·keys are the fixed labels; values are ordinary data. The last pair can skip its comma. Curly braces make an OBJECT — square brackets [ ] would make an array (Class 17)
REAL OUTPUT — PLAIN PAGE, THEN CSS, THEN THE OBJECT BUILDS
file:///C:/Users/student/Desktop/fswd-practice/Class-15/literal.html

Object literal syntax

Open the Console (F12) to watch the object build.

PLAIN HTML — NO CSS AND NO SCRIPT YET
DEVTOOLS · CONSOLE — PROPERTY BY PROPERTY
// dish opened — no properties yet
{ name: 'Millet Khichdi' }
{ name: 'Millet Khichdi', price: 90 }
{ name: 'Millet Khichdi', price: 90, category: 'bowl' }
{ name: 'Millet Khichdi', price: 90, category: 'bowl', isMillet: true }
// object closed — dish is now a complete value
› { name: 'Millet Khichdi', price: 90, category: 'bowl', isMillet: true }
HTML made the page, CSS dressed it, and only then did the object literal exist. The braces produced a genuine value — you can see it printed in full on the second surface.

A second, unrelated example — the same shape, a different world

The object shape isn't just for food. Here's a throwaway example modelling a library book — completely different data, exactly the same { key: value } rules. And it gets its own page built from scratch, because a .js file still cannot run by itself: plain HTML → CSS → JS, every time.

book.html + style rules + book.js · plain HTML → CSS → JSHTML, THEN CSS, THEN JS — ONE PRESS PER LINE
·<!-- FILE 1 of 3 · book.html — plain HTML first, always -->
1<!DOCTYPE html>
2<html lang="en">
3<head>
4 <meta charset="UTF-8">
5 <title>Library book</title>
6</head>
7<body>
8 <h1>Campus Library</h1>
9 <p class="tip">The book object prints in the Console (F12).</p>
10</body>
11</html>
·/* HTML complete & PLAIN above. FILE 2 of 3 · the CSS — one rule per press ↓ */
6 <style>
7 body { font-family: Georgia, serif; padding: 18px; }
8 h1 { color: #B45309; font-size: 20px; }
9 .tip { color: #64748B; font-size: 13px; }
10 </style>
·<!-- CSS done. Hire the passenger — last line before </body> -->
11 <script src="book.js"></script>
·// ————— FILE 3 of 3 · book.js — same rules, a different world —————
1// same object rules, a totally different thing
2const book = {
3 title: "Wings of Fire",
4 author: "A.P.J. Abdul Kalam",
5 pages: 180,
6 available: false
7};
8console.log(book);
·string, string, number, boolean — the values differ, but the object's shape is identical to the dish's. Learn the shape once, reuse it everywhere
REAL OUTPUT — PLAIN PAGE, THEN CSS, THEN THE BOOK OBJECT
file:///C:/Users/student/Desktop/fswd-practice/Class-15/book.html

Campus Library

The book object prints in the Console (F12).

PLAIN HTML — NO CSS AND NO SCRIPT YET
DEVTOOLS · CONSOLE — KEY BY KEY
// book opened
{ title: 'Wings of Fire' }
{ title: 'Wings of Fire', author: 'A.P.J. Abdul Kalam' }
{ title: 'Wings of Fire', author: 'A.P.J. Abdul Kalam', pages: 180 }
{ title: 'Wings of Fire', author: 'A.P.J. Abdul Kalam', pages: 180, available: false }
// object closed
› { title: 'Wings of Fire', author: 'A.P.J. Abdul Kalam', pages: 180, available: false }
A different page, a different colour, completely different data — and the same three-stage build. That repetition is deliberate: plain HTML → CSS → JavaScript is the habit, not a one-off.

Prove it — build a real object right here

This console genuinely runs in your browser. Type an object literal, or tap a quick-fill button, and press Enter — JavaScript builds the real object and prints it back. Try changing a value and re-running.

DevTools · Console — LIVE & REAL · type an object, press Enter
EXTRA DEPTH · WHY THE PARENTHESES?

In the console we wrap the object in ( ) — like ({ name: "Veg Samosa" }). Without them, a leading { looks to JavaScript like the start of a code block, not an object. The parentheses say "this is a value, an object literal". Inside a normal const dish = { … } statement you never need them — the = already makes it clear a value is coming.

Reach inside the container

Two ways to read one property — dot . and bracket [ ].

Building the object is half the job; the other half is reading a fact back out. JavaScript gives you two notations, and they return the exact same value: dot notationdish.price — clean and readable, the one you'll use 95% of the time; and bracket notationdish["price"] — where the key goes in quotes inside square brackets. Both hand you 90.

NotationLooks likeReach for it when…
dotdish.priceyou know the key name as you type — the everyday choice. Cleaner, shorter, easier to read.
bracketdish["price"]the key is stored in a variable, or has spaces/special characters. e.g. dish[chosenKey].

See both notations return the same value — click a key, live

This is real: a genuine object dish lives in the page. Click any key below and watch both dish.key and dish["key"] read the same real value out of it. No faked strings — the widget actually reads the object.

THIS IS REAL — CLICK A KEY, BOTH NOTATIONS ANSWER
const dish = {
  name: "Millet Khichdi",
  price: 90,
  category: "bowl",
  isMillet: true
};
DOT NOTATIONdish.name
BRACKET NOTATIONdish["name"]
BOTH RETURN"Millet Khichdi"
Both dish.name and dish["name"] return the same value: "Millet Khichdi".
Watch a real gotcha: dish.price works, but dish["price"] needs the quotesdish[price] without quotes would look for a variable called price, not the key. That's exactly why bracket notation is the tool for keys-held-in-variables.

In code, side by side — built from scratch, HTML → CSS → JS

The page first (plain, then two CSS rules), then the script. The script reads the same two facts twice — once with dots, once with brackets — and the Console proves the pairs are identical.

access.html + style rules + script.js · plain HTML → CSS → JSHTML, THEN CSS, THEN JS — ONE PRESS PER LINE
·<!-- FILE 1 of 3 · access.html — plain HTML first -->
1<!DOCTYPE html>
2<html lang="en">
3<head>
4 <meta charset="UTF-8">
5 <title>Dot vs bracket</title>
6</head>
7<body>
8 <h1>Reading properties</h1>
9 <p class="tip">Both notations print in the Console (F12).</p>
10</body>
11</html>
·/* HTML complete & PLAIN above. FILE 2 of 3 · the CSS — one rule per press ↓ */
6 <style>
7 body { font-family: Georgia, serif; padding: 18px; }
8 h1 { color: #0E7490; font-size: 20px; }
9 .tip { color: #64748B; font-size: 13px; }
10 </style>
·<!-- CSS done. Hire the passenger — last line before </body> -->
11 <script src="script.js"></script>
·// ————— FILE 3 of 3 · script.js — dot and bracket, same object —————
1const dish = { name: "Millet Khichdi", price: 90 };
2// dot notation
3console.log(dish.name); // Millet Khichdi
4console.log(dish.price); // 90
5// bracket notation — same values
6console.log(dish["name"]); // Millet Khichdi
7console.log(dish["price"]); // 90
REAL OUTPUT — PLAIN PAGE, THEN CSS, THEN BOTH NOTATIONS PRINT
file:///C:/Users/student/Desktop/fswd-practice/Class-15/access.html

Reading properties

Both notations print in the Console (F12).

PLAIN HTML — NO CSS AND NO SCRIPT YET
DEVTOOLS · CONSOLE
Millet Khichdidish.name
90dish.price
Millet Khichdidish["name"]
90dish["price"]
↑ identical pairs — the notation changes, the value never does
Four Console lines, two identical pairs. Dot and bracket are two spellings of the same read — pick dot unless the key lives in a variable or contains spaces.

Exam drill · straight from a past paper

"Add a city property to this object — two ways."

This is a real 2-mark question. It gives you an object and asks you to add a new property to it — once with dot notation, once with bracket notation. It's the mirror image of reading a property: instead of = pulling a value out, you put a value in. Reveal the model answer one point at a time.

PREVIOUS YEAR QUESTION PAPER 2 Q4 2 MARKS

2 ways = 2 marksQ4. Given let user = {name:'Karan', age:21}; — add a property city with value 'Hyderabad' using both dot and bracket notation. (2 M)

Model answer — reveal one point per press ▸
1
Dot notation: user.city = 'Hyderabad'; — name the new key straight after the dot and assign it. ✓ 1 m
2
Bracket notation: user['city'] = 'Hyderabad'; — the key goes in quotes inside brackets. ✓ 1 m
3
Both do the same thing — if the key doesn't exist yet, assigning to it creates it. user becomes {name:'Karan', age:21, city:'Hyderabad'}.
Model program to attach (locks the full 2 marks):
script.js
let user = { name: 'Karan', age: 21 };
user.city = 'Hyderabad'; // dot
user['city'] = 'Hyderabad'; // bracket (same result)
console.log(user);
{ name: 'Karan', age: 21, city: 'Hyderabad' }
0 / 4

Notice this uses let user, not const — but we still add a property. Adding or changing a property inside an object is allowed even with const; what const forbids is re-pointing the whole variable to a different object. So const user = {…}; user.city = 'Hyderabad'; is perfectly legal. The exam happened to use let, but either works here.

BUILD-FROM-SPEC ACTIVITY

Turn a written spec into an object literal.

Here is a plain-English spec for one dish. Your job: write it as a single object literal, picking the right data type for each fact. Attempt it in your own fswd-practice\Class-15\script.js first — then open the solution and check line by line.

THE SPEC — model this dish as one object called dish
name
the text "Paneer Tikka"
price
the number 120 (rupees — no quotes, it's a number)
category
the text "starter"
isMillet
the yes/no false (it is not a millet dish)
THEN
print the whole object, and print just its price with dot notation

Write your object first — even a rough attempt teaches more than reading the answer cold.

activity.html + style rules + script.js · model solution, plain HTML → CSS → JSHTML, THEN CSS, THEN JS — ONE PRESS PER LINE
·<!-- FILE 1 of 3 · activity.html — plain HTML first, as always -->
1<!DOCTYPE html>
2<html lang="en">
3<head>
4 <meta charset="UTF-8">
5 <title>Class 15 activity</title>
6</head>
7<body>
8 <h1>Paneer Tikka</h1>
9 <p class="tip">The object prints in the Console (F12).</p>
10</body>
11</html>
·/* HTML complete & PLAIN above. FILE 2 of 3 · the CSS — one rule per press ↓ */
6 <style>
7 body { font-family: Georgia, serif; padding: 18px; }
8 h1 { color: #BE185D; font-size: 20px; }
9 .tip { color: #64748B; font-size: 13px; }
10 </style>
·<!-- CSS done. Hire the passenger — last line before </body> -->
11 <script src="script.js"></script>
·// ————— FILE 3 of 3 · script.js — the object the task asked for —————
1const dish = {
2 name: "Paneer Tikka", // string
3 price: 120, // number — no quotes
4 category: "starter", // string
5 isMillet: false // boolean — last, no comma
6};
7console.log(dish);
8console.log(dish.price);
REAL OUTPUT — PLAIN PAGE, THEN CSS, THEN THE OBJECT
file:///C:/Users/student/Desktop/fswd-practice/Class-15/activity.html

Paneer Tikka

The object prints in the Console (F12).

PLAIN HTML — NO CSS AND NO SCRIPT YET
DEVTOOLS · CONSOLE
// dish opened
{ name: 'Paneer Tikka' }
{ name: 'Paneer Tikka', price: 120 }
{ name: 'Paneer Tikka', price: 120, category: 'starter' }
{ name: 'Paneer Tikka', price: 120, category: 'starter', isMillet: false }
› { name: 'Paneer Tikka', price: 120, category: 'starter', isMillet: false }
› 120
Full marks looks like this: page loads plain, gains its three CSS rules, then the Console shows the complete object and 120 (a number, not "120") with no red.

Marking your own work: did you quote the strings but leave 120 and false unquoted? Did the last pair skip its comma (or keep it — both are fine)? Did dish.price print 120, not "120"? If yes to all, your object is spec-perfect.

A value can be an action

A property can hold a function. When it does, we call it a method.

So far every value in our object has been data — a string, a number, a boolean. But a value can also be a function. A function stored as a property is called a method: an action the object can do, not just a fact it holds. Our dish can now not only have a name and price — it can describe itself.

Meet this — at the minimum depth you need today. Inside a method, the keyword this means "the object this method belongs to". So inside dish's method, this.name means dish.name. That's all you need for this course — the deeper rules about how this binds in other situations are out of syllabus scope, so we deliberately stop here.

A dish that can describe itself — built from scratch, HTML → CSS → JS

Page first (plain, then three CSS rules one press at a time), then the script. The object gets a method called describe. Calling it with dish.describe() (note the parentheses — that's how you run a function) makes the Console print a sentence built from the object's own properties, via this.

method.html + style rules + script.js · plain HTML → CSS → JSHTML, THEN CSS, THEN JS — ONE PRESS PER LINE
·<!-- FILE 1 of 3 · method.html — plain HTML first -->
1<!DOCTYPE html>
2<html lang="en">
3<head>
4 <meta charset="UTF-8">
5 <title>Objects with methods</title>
6</head>
7<body>
8 <h1>A dish that describes itself</h1>
9 <p class="tip">The method's sentence appears in the Console (F12).</p>
10</body>
11</html>
·/* HTML complete & PLAIN above. FILE 2 of 3 · the CSS — one rule per press ↓ */
6 <style>
7 body { font-family: Georgia, serif; padding: 18px; }
8 h1 { color: #047857; font-size: 20px; }
9 .tip { color: #64748B; font-size: 13px; }
10 </style>
·<!-- CSS done. Hire the passenger — last line before </body> -->
11 <script src="script.js"></script>
·// ————— FILE 3 of 3 · script.js — an object with a method —————
1const dish = {
2 name: "Millet Khichdi",
3 price: 90,
4 // a property whose value is a FUNCTION = a method
5 describe: function() {
6 return `${this.name} costs Rs.${this.price}`;
7 }
8};
9console.log(dish.describe()); // call it with ()
·this.name and this.price reach back into the SAME object. dish.describe() RUNS the method; dish.describe (no parens) would just print the function itself
REAL OUTPUT — PLAIN PAGE, THEN CSS, THEN THE METHOD RUNS
file:///C:/Users/student/Desktop/fswd-practice/Class-15/method.html

A dish that describes itself

The method's sentence appears in the Console (F12).

PLAIN HTML — NO CSS AND NO SCRIPT YET
DEVTOOLS · CONSOLE
// describe defined — not run yet
› Millet Khichdi costs Rs.90
↑ the sentence this built, from the object's own two properties
Notice the gap between defining the method (nothing printed) and calling it with () — that's the whole difference between owning a recipe and cooking it.
EXTRA DEPTH · WHY this AND NOT JUST name?

Inside the method you must write this.name, not bare name. Bare name would look for a variable called name in the surrounding code — not the object's property. this. is the bridge from "inside the method" back to "the object I live on". Change dish.name later and describe() automatically reflects it, because it reads the property fresh every time it runs.

PREDICT-THE-OUTPUT ACTIVITY

Read the object and the console.log lines — predict every printed value.

Below is an object and five console.log lines. Cover the right side, read each line, and write down what you think it prints — before you reveal. This is the single best drill for objects: it forces you to trace dot access, bracket access, a method call, and a missing key.

THE PROGRAM — predict each line's output
OBJECT
const car = { brand: "Tata", seats: 5, isElectric: true, honk: function(){ return "Beep!"; } };
LINE 1
console.log(car.brand);
LINE 2
console.log(car["seats"]);
LINE 3
console.log(car.isElectric);
LINE 4
console.log(car.honk());
LINE 5
console.log(car.colour);  ← careful — this key was never set

Commit to all five predictions first — especially line 5.

predict.html + style rules + script.js · the program in full, plain HTML → CSS → JSHTML, THEN CSS, THEN JS — ONE PRESS PER LINE
·<!-- FILE 1 of 3 · predict.html — the page that runs the five lines -->
1<!DOCTYPE html>
2<html lang="en">
3<head>
4 <meta charset="UTF-8">
5 <title>Predict the output</title>
6</head>
7<body>
8 <h1>Tata — car object</h1>
9 <p class="tip">All five answers appear in the Console (F12).</p>
10</body>
11</html>
·/* HTML complete & PLAIN above. FILE 2 of 3 · the CSS — one rule per press ↓ */
6 <style>
7 body { font-family: Georgia, serif; padding: 18px; }
8 h1 { color: #1D4ED8; font-size: 20px; }
9 .tip { color: #64748B; font-size: 13px; }
10 </style>
·<!-- CSS done. Hire the passenger — last line before </body> -->
11 <script src="script.js"></script>
·// ————— FILE 3 of 3 · script.js — the five lines you predicted —————
1const car = { brand: "Tata", seats: 5,
2 isElectric: true, honk: function(){ return "Beep!"; } };
3console.log(car.brand); // dot
4console.log(car["seats"]); // bracket
5console.log(car.isElectric); // boolean
6console.log(car.honk()); // method call
7console.log(car.colour); // missing key!
REAL OUTPUT — PLAIN PAGE, THEN CSS, THEN ALL FIVE ANSWERS
file:///C:/Users/student/Desktop/fswd-practice/Class-15/predict.html

Tata — car object

All five answers appear in the Console (F12).

PLAIN HTML — NO CSS AND NO SCRIPT YET
DEVTOOLS · CONSOLE — THE REAL OUTPUT
Tatacar.brand
5car["seats"]
truecar.isElectric
Beep!car.honk()
undefinedcar.colour ✗
Five lines, five answers — and line 5 printed undefined in yellow rather than crashing. Notice the visible page never changed: console.log only ever writes to the second surface.

Line 5 is the trap. Reading a key that was never set doesn't crash — JavaScript quietly returns undefined. That's very different from a typo in a method call or reading a property of undefined, which do throw. Remember: missing key → undefined, no error. And car.honk() needs its parentheses — without them you'd print the function itself, not "Beep!".

A value can be another object

Nested objects — an object living inside a property of another object.

You've seen values that are strings, numbers, booleans, and functions. A value can also be a whole other object. When a dish's nutrition is itself a bundle of facts — protein, calories — it makes sense to store it as its own little object, tucked inside the dish. To read a fact two levels deep, you just chain the dots: dish.nutrition.protein.

A dish with a nutrition sub-object — built from scratch, then stepped through

Same rule as every JavaScript demo in this course: a .js file cannot be double-clicked into life, so we build its host page first — plain HTML, then a little CSS, then the script. Then step through and watch the Console. The outer object dish holds a normal name and price — and a nutrition property whose value is a second object. Reading into it is just dots all the way down.

nested.html + style rules + script.js · an object inside an object, plain HTML → CSS → JSHTML, THEN CSS, THEN JS — ONE PRESS PER LINE
·<!-- FILE 1 of 3 · nested.html — the page that hosts the nested object -->
1<!DOCTYPE html>
2<html lang="en">
3<head>
4 <meta charset="UTF-8">
5 <title>Nested objects</title>
6</head>
7<body>
8 <h1>Millet Khichdi — nutrition</h1>
9 <p class="tip">Open the Console (F12) to see the sub-object.</p>
10</body>
11</html>
·/* HTML complete & PLAIN above. FILE 2 of 3 · the CSS — one rule per press ↓ */
6 <style>
7 body { font-family: Georgia, serif; padding: 18px; }
8 h1 { color: #0F766E; font-size: 20px; }
9 .tip { color: #64748B; font-size: 13px; }
10 </style>
·<!-- CSS done. Hire the passenger — last line before </body> -->
11 <script src="script.js"></script>
·// ————— FILE 3 of 3 · script.js — an object inside an object —————
1const dish = {
2 name: "Millet Khichdi",
3 price: 90,
4 nutrition: { // a whole object as a value
5 protein: 12, // grams
6 calories: 320
7 }
8};
9console.log(dish.nutrition); // the sub-object
10console.log(dish.nutrition.protein); // two levels deep
·chain the dots: dish → nutrition → protein. Each dot steps one level in. Bracket works too: dish["nutrition"]["protein"]
REAL OUTPUT — PLAIN PAGE, THEN CSS, THEN THE NESTED READS
file:///C:/Users/student/Desktop/fswd-practice/Class-15/nested.html

Millet Khichdi — nutrition

Open the Console (F12) to see the sub-object.

PLAIN HTML — NO CSS AND NO SCRIPT YET
DEVTOOLS · CONSOLE — THE REAL OUTPUT
// nutrition sub-object being built…
{ protein: 12, calories: 320 }dish.nutrition
12dish.nutrition.protein
Two surfaces again: the page above shows only the <h1> and the tip you typed, while the Console below shows the object inside the object. One dot reached nutrition; a second dot reached protein.
dish (outer object) name: "Millet Khichdi" price: 90 nutrition: ─────────► nutrition (inner object) protein: 12 calories: 320 dish.nutrition.protein → step in twice → 12
EXTRA DEPTH · GUARD AGAINST GOING TOO DEEP ON A MISSING KEY

dish.nutrition.protein is fine because nutrition exists. But dish.allergens.count would throw Cannot read properties of undefined — because dish.allergens is undefined, and you can't read .count off undefined. Reading one missing key is safe (gives undefined); reading into a missing key crashes. You'll meet the safe fix (optional chaining ?.) in a later class.

Self-study · a light preview

Object or array? A quick-decision reference.

You'll meet arrays in full next class (Class 17), but you'll already sense the choice: an object stores facts you look up by name (dish.price); an array stores a list of items you look up by position (menu[0]). This is a self-study card — skim it now, and it'll click fully once arrays land.

DECISION TABLE · OBJECT vs ARRAY (full arrays = Class 17)
QuestionObject { }Array [ ]
Shapenamed labels → valuesan ordered list of items
Look up by…namedish.pricepositionmenu[0]
Best forone thing with many facts (a dish, a user)many things of the same kind (a whole menu)
Order matters?no — keys aren't positionalyes — item 0, item 1, item 2…
Example{ name:"Khichdi", price:90 }["Khichdi", "Samosa", "Chai"]

The rule of thumb: if you'd describe the data as "a list of…", reach for an array. If you'd describe it as "one thing with a name, a price, a…", reach for an object. And the two combine beautifully — a whole menu is naturally an array of objects: [ {name:"Khichdi",price:90}, {name:"Samosa",price:20} ]. That exact combination is the first thing you'll build in Lab 4.

Put it all together — a real console

Practise everything from today in a genuine JavaScript console.

This console truly runs in your browser — build an object, read it with dot and bracket, call a method, add a property, read a missing key. Tap a quick-fill to see each idea from today prove itself, then type your own. Copy any of these into your fswd-practice\Class-15\script.js and run them with F12 → Console.

DevTools · Console — LIVE & REAL · type an expression, press Enter

Two traps that catch everyone — read the real errors

These are the two mistakes you'll make in your first hour with objects. Read the exact console messages so you recognise them instantly.

ConsoleSourcesNetwork
› const dish = { name: "Khichdi" };
› dish.colour;
undefined  // missing key — no crash, just undefined
› dish.nutrition.protein;
Uncaught TypeError: Cannot read properties of undefined (reading 'protein')
script.js:3
Trap 1 (safe): reading a key that isn't there gives undefined, no error. Trap 2 (crash): reading into a key that is undefined throws Cannot read properties of undefined — because dish.nutrition doesn't exist, so .protein has nothing to read from. Fix: make sure the sub-object exists first.

Wrap-up & the bridge to Class 16

Your data now has shape. Next class, JavaScript reaches out and changes the page itself.

Today one box learned to hold many labelled facts — a dish's name, price, category, millet-flag — read two ways, given a method, and nested one object inside another. But an object still only lives in memory. Class 16 introduces the DOM: the browser's live model of your HTML, so JavaScript can find an element on the page and change its text, its style, anything. Objects are the data; the DOM is the page. Lab 4 puts both to work together.

YOUR THROWAWAY SANDBOX TODAY
fswd-practice/  · scratch paper — never a repo, never committed
Class-15/
script.js  ← today's practice: object literals, dot/bracket access, methods, nested objects
A single throwaway file, zero commits. You drilled objects on scratch paper in VS Code (open the file, edit it, press F12 → Console to run it) — the same skill you'll later use in the real poshtik-campus\ project during the labs, where the continuous build is what actually gets committed.

Take-home kit — the object cheat-card

Copy this into your notes. It answers every object exam question you saw today in a single glance.

  • Object literal: const dish = { name: "Khichdi", price: 90 };{ key: value } pairs, comma-separated.
  • Read two ways: dot dish.price (everyday) and bracket dish["price"] (when the key is in a variable). Same value.
  • Add / change: dish.city = "Hyderabad" creates the key if missing — allowed even on a const object (P2·Q4).
  • Method: a property whose value is a function; inside it, this.name means "this object's name". Call it with dish.describe().
  • Nested + missing keys: dish.nutrition.protein chains dots; a missing key reads as undefined (safe), but reading into undefined throws.
Before you leave — say these out loud (self-test)
  1. Write an object literal for a dish with a name, a price, and an isMillet flag.
  2. Read that dish's price two ways — dot and bracket notation.
  3. Given let user={name:'Karan',age:21}, add city:'Hyderabad' both ways (P2·Q4).
  4. What is a method, and what does this mean inside one?
  5. What does reading a key that was never set return — and when does reading a nested key crash instead?