Class 14 — the page learns to remember
Last class your page said "hello". Today it learns to hold on to a name, a price, a yes-or-no.
In Class 13 you wrote one line — console.log("Hello from script.js!") — and the browser printed it. But that message vanished the instant it was printed; the page kept nothing. Real programs need memory: a place to put a value now and use it again later. That place is called a variable — a labelled box you fill once and reach for as often as you like. Today you learn the three words that make a box (let, const, var), the kinds of things a box can hold (its data types), and one legacy oddity — the with statement — that an exam may still ask you to read.
Walk out of this room able to…
Same as last class: every demo runs live, right on this slide. To practise on your own machine, make a fresh throwaway folder fswd-practice\Class-14\, 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, where companion download packs are used. 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.
The idea, in one plain sentence
A variable is a labelled box. You put a value in once; you use the label forever.
Imagine writing the Poshtik Campus welcome message. The student's name — say "Trishaank" — needs to appear in the heading, again in the greeting, and once more in the order confirmation. Without a variable you'd type the word three times. Change your mind (or the student logs in as someone else) and you'd have to find and fix all three by hand. A variable fixes this: write the name once into a box, give the box a label, and everywhere you want the name you just write the label.
studentName, not x. The label is how you'll reach the value later.= sign: studentName = "Trishaank". In JavaScript = means "put the right side into the left", not "equals".studentName, JavaScript swaps in whatever's inside the box right now.See the payoff — one box, used three times
Here is the full, from-scratch program. Step through it one line per press. Notice: the name "Trishaank" is typed exactly once (line 2). Every later line just uses the label.
// store the name in a box called studentNamelet studentName = "Trishaank";console.log("Welcome, " + studentName + "!");console.log(studentName + ", your cart is ready.");console.log("Order confirmed for " + studentName);the value "Trishaank" was typed ONCE. Change line 2 to "Aditi" and all three messages update together — that is the whole point of a variableThe + between text pieces here is string concatenation — it glues text together. It works, but it gets ugly fast with lots of pieces and stray spaces. In Part 8 you'll meet a cleaner way to build the same sentence: the template literal. For now, concatenation with + is perfectly correct.
Hold on — where does that script.js actually live?
Fair question, and we should answer it once, properly, before six more panels go by. Every panel today is captioned script.js — but a .js file cannot run on its own by double-clicking it. A browser only runs JavaScript that a web page hands it. So here is the host page, built from scratch — and it is deliberately tiny. We need exactly two things from HTML today: a page that loads, and a <script> tag that points at our file. Nothing more, because today's lesson is about variables, not markup. You built far richer pages than this all through Unit 1.
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Class 14 practice</title></head><body> <h1>Open DevTools — the answers are in the Console</h1> <script src="script.js"></script> <!-- ← the ONE line that matters --></body></html>/* HTML is complete & plain above. Two comfort rules, so the page isn't raw ↓ */ body { font-family: Georgia, serif; padding: 20px; } h1 { color: seagreen; font-size: 20px; }Line 9 is the whole point: it tells the browser "there is a file called script.js next to me — run it." The two CSS lines are the ONLY styling today's concept needs. Save both files in the SAME folder.Plain heading first, then the page gains Georgia + padding, then the heading turns seagreen. That is the whole visible surface today — everything else happens in the Console.
The two-file habit, learnt once and reused all unit. Class 13 already had you wire a page to a script with <script src="script.js"> just before </body> — this is the same move, and it will be the same move in Class 15, Class 16 and every lab. So we will not reprint this page again: from here on, whenever a panel says script.js, picture this 11-line page sitting beside it. The only file that changes today is script.js.
fswd-practice\Class-14\ and open it in VS Code.practice.html (type all 11 lines above) and an empty script.js.script.js, save both, double-click practice.html, then press F12 and click the Console tab. Your three lines are there.script.js, so the file must be named exactly that, in the same folder.Three words that make a box
let, const, and var — pick the right one and half your bugs never happen.
JavaScript gives you three keywords to declare a variable. They differ in one simple question: can the box's contents change later, and where can the box be seen? This course uses let and const only — the modern ES6 pair — and shows you var exactly once, so you can recognise it in old code and understand why it caused surprises.
| Keyword | Can you re-assign it? | Use it when… |
|---|---|---|
| const | No — fixed once set | the value should never change: a price, a tax rate, a fixed label. Reach for const first, every time. |
| let | Yes — can change | the value genuinely changes over the program: a score, a counter, a running total. |
| var | Yes (but leaky) | Avoid. The old (pre-2015) keyword. Shown here only so you can read old code and the exam's with question. |
const vs let, side by side — one changes, one refuses
JavaScript never runs alone, so we build the whole thing from scratch, in the one order you will use all course: plain HTML first → then CSS, one rule per press → then the script. The page is deliberately small (a heading and two lines of text), because today's idea lives in the Console. Watch the white page grow, and then watch the dark Console strip: the const line refuses to change and throws a real error; the let line changes happily. That contrast is the difference.
<!-- FILE 1 of 3 · const-vs-let.html — the page that will CARRY the script --><!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>const vs let</title></head><body> <h1>Poshtik Cart</h1> <p>Samosa price: ₹20</p> <p>Items in cart: 1</p></body></html>/* HTML is complete & PLAIN above. FILE 2 of 3 · the CSS — one rule per press ↓ */ <style> /* typed back up in the <head> */ body { font-family: Georgia, serif; padding: 20px; } h1 { color: seagreen; } p { color: #334155; font-size: 15px; } </style><!-- CSS done. Now hire the passenger — last line before </body> --> <script src="script.js"></script>// ————— FILE 3 of 3 · script.js — const refuses, let allows —————// const — a value that must NOT changeconst samosaPrice = 20;console.log(samosaPrice); // 20// try to change it — JavaScript refuses:samosaPrice = 25; // TypeError: Assignment to constant variable.// let — a value that is SUPPOSED to changelet itemsInCart = 1;itemsInCart = itemsInCart + 1; // now 2 — allowedconsole.log(itemsInCart); // 2Poshtik Cart
Samosa price: ₹20
Items in cart: 1
PLAIN HTML — NO CSS AND NO SCRIPT YETconst can never be re-assigned.let box happily changed from 1 to 2.The one time we show var — the scoping surprise (§1.7 error-first). Old code used var everywhere. The trap: a var declared inside a block (an if, a loop) leaks out of that block and is visible to the whole surrounding function. let and const stay politely inside their { }. This leak is exactly the kind of scope-bending behaviour that also powers the legacy with statement you'll read in Part 11 — same family, same reason we avoid both.
Inside if (true) { var a = 1; let b = 2; } — after the block, console.log(a) prints 1 (the var leaked out), but console.log(b) throws ReferenceError: b is not defined (the let stayed inside). That single difference is why every modern style guide — and this course — says: never var, always let/const.
A fresh, throwaway world — why let exists, seen in slow motion
Forget the food site for a moment — every code snippet is a tiny, disposable world we invent just to see one idea. This one is a rocket launch countdown. Watch a single let box named seconds hold a value, then get re-assigned lower and lower. Because the number is supposed to change, let is exactly right — and a const here would refuse.
"This is pure JavaScript — so where do I even look?" Honest answer: a .js file cannot be double-clicked into life, so even a pure-JS idea still needs a host page. We build that page from scratch — plain HTML first, then CSS, then the script — and it stays deliberately plain, because the countdown itself prints to the Console, not to the page. So you get two output surfaces to look at: the white page (HTML + CSS) and the dark Console (JavaScript).
<!-- FILE 1 of 3 · launch.html — the plain page that carries launch.js --><!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Launch countdown</title></head><body> <h1>Launch countdown</h1> <p>Open the Console (F12) — the countdown prints there.</p></body></html>/* HTML complete & PLAIN above. FILE 2 of 3 · the CSS — one rule per press ↓ */ <style> /* typed back up in the <head> */ body { font-family: Georgia, serif; padding: 20px; } h1 { color: #1D4ED8; font-size: 22px; } </style><!-- CSS done. Hire the passenger — last line before </body> --> <script src="launch.js"></script>// ————— FILE 3 of 3 · launch.js — one let box, re-assigned —————// a value that is MEANT to change → use letlet seconds = 3;console.log("T minus " + seconds);seconds = seconds - 1; // re-assign: 3 → 2console.log("T minus " + seconds);seconds = seconds - 1; // re-assign: 2 → 1console.log("T minus " + seconds);seconds = 0;console.log("Lift-off! 🚀");Launch countdown
Open the Console (F12) — the countdown prints there.
PLAIN HTML — NO CSS AND NO SCRIPT YETProve it — run pure JavaScript right here. This console is genuinely running in your browser. Press a button (or type your own) and watch a real let box change — and see what happens the instant you try to re-assign a const.
Exam drill · straight from a past paper
"Describe the use of let and const."
This is a real 4-mark question. Four marks means the examiner wants four distinct, scorable points — and a tiny code example seals it. Reveal the model answer one point at a time and copy the shape into your own words.
4 marks = 4 pointsQ12(a). Describe the use of let and const in JavaScript. (4 M)
{ } where declared — which makes them safer than the older var. ✓ 1 mWhat can a box hold?
Five everyday kinds of value — string, number, boolean, undefined, null.
A box can hold different kinds of things, and JavaScript treats each kind — each data type — a little differently. You only need five to start, and you already met all of them in plain life: words, numbers, yes/no, "nothing set yet", and "deliberately empty".
| Data type | What it holds | Poshtik Campus example |
|---|---|---|
| string | text, always in quotes | "Veg Samosa" — a dish name |
| number | any number, whole or decimal | 20 — a price in rupees |
| boolean | exactly two values: true / false | true — is the dish in stock? |
| undefined | a box declared but never filled | let coupon; — no coupon set yet |
| null | "deliberately empty", set on purpose | let selected = null; — nothing chosen |
undefined vs null — the one that trips everyone. undefined is what JavaScript gives a box you made but never filled — the language put it there. null is what you put in a box to say "empty on purpose". Rule of thumb: undefined = forgotten, null = chosen.
All five, declared in one file — built from scratch, HTML → CSS → JS
Same order every time, no shortcuts: we type the plain HTML page first (a tiny dish card), then add CSS one rule per press so you can see each rule land, then finally the script that declares one box of each data type and prints them. Two surfaces to watch on the right: the white card, and the dark Console underneath it.
<!-- FILE 1 of 3 · types.html — plain HTML, nothing styled yet --><!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Five data types</title></head><body> <h1>Poshtik Campus — dish card</h1> <div class="dish"> <h2>Veg Samosa</h2> <p class="price">₹20</p> <p class="stock">In stock</p> </div></body></html>/* HTML complete & PLAIN above. FILE 2 of 3 · the CSS — one rule per press ↓ */ <style> /* typed back up in the <head> */ body { font-family: Georgia, serif; padding: 18px; } h1 { font-size: 18px; color: #334155; } .dish { border: 2px solid seagreen; padding: 12px; } .price { color: seagreen; font-weight: bold; } .stock { color: #15803D; font-size: 13px; } </style><!-- CSS done. Hire the passenger — last line before </body> --> <script src="script.js"></script>// ————— FILE 3 of 3 · script.js — one box of each type —————const dishName = "Veg Samosa"; // stringconst price = 20; // numberconst inStock = true; // booleanlet coupon; // undefined — declared, not filledlet selected = null; // null — deliberately emptyconsole.log(dishName);console.log(price);console.log(inStock);console.log(coupon);console.log(selected);Poshtik Campus — dish card
Veg Samosa
₹20
In stock
Exam drill · a quick 2-marker
"Name four data types in JavaScript."
A short, guaranteed 2 marks — but only if you name them precisely and give a one-word example each. Reveal the model answer point by point.
name + example eachQ3. Name four data types in JavaScript. (2 M)
"Veg Samosa".20.true or false.Sort six Poshtik Campus values into their data types.
Below are six real values from the Poshtik Campus app. For each, decide its data type. Try it in your head (or on paper) first — then open the solution and check. This is exactly the recognition the P4·Q3 exam rewards.
"Masala Chai" — a dish name15 — its price in rupeestrue — is it available today?let cart; — a cart the student hasn't opened yet4.5 — the dish's star ratinglet chosenTable = null; — no table picked on purposeCommit to your six answers first. Answer honestly — that's how the recognition sticks.
"Masala Chai" → string — it's text, and it wears quotes.15 → number — a whole number, no quotes.true → boolean — one of the only two boolean values.let cart; → undefined — declared, never filled; JavaScript put undefined inside.4.5 → number — decimals are still the number type in JavaScript (there's no separate "float").null → null — deliberately empty, set by you, not by the language.The trap in this set: D and F look similar but are different types. undefined (D) happens because you never filled the box; null (F) is you filling it with "empty" on purpose. undefined = forgotten, null = chosen.
Ask a value what it is
Not sure what type a value is? typeof tells you — at runtime.
You won't always be able to eyeball a type — especially once values come from a form or a server. JavaScript has a built-in helper: put typeof in front of any value and it hands back a string naming the type. Click each value below and watch typeof answer, live.
typeof null returns "object", not "null" — a decades-old bug the language kept for compatibility. Worth knowing so it never surprises you; not worth losing sleep over.Try it yourself — a real, live JavaScript console
This is a genuine JavaScript console, not a picture. Type typeof 20 and press Enter, or tap a quick-fill button. It runs your line for real and prints the true result.
Build a sentence from variables — cleanly
Template literals — drop a variable straight into text with ${ }.
Remember gluing text with + back in Part 2? It works, but the quotes and spaces get fiddly. ES6 added a cleaner tool: wrap your text in backticks ` ` (the key above Tab, left of 1) instead of quotes, and drop any variable inside with ${ }. JavaScript swaps in the value automatically. Full string-method depth comes in Class 18 — today you only need this one, genuinely variable-adjacent, ES6 feature.
Built from scratch in the usual order — plain HTML, then CSS one rule per press, then the script. The page is a small greeting card so you can see the HTML and CSS do their job; the two versions of the sentence print into the Console below it, and they print identically. That's the point: same output, cleaner code.
<!-- FILE 1 of 3 · greet.html — plain HTML first --><!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Template literals</title></head><body> <h1>Greeting card</h1> <p class="hint">The sentence is built in script.js — see the Console.</p></body></html>/* HTML complete & PLAIN above. FILE 2 of 3 · the CSS — one rule per press ↓ */ <style> /* typed back up in the <head> */ body { font-family: Georgia, serif; padding: 18px; } h1 { color: #B45309; font-size: 20px; } .hint { color: #64748B; font-size: 13px; } </style><!-- CSS done. Hire the passenger — last line before </body> --> <script src="script.js"></script>// ————— FILE 3 of 3 · script.js — old glue vs template literal —————const name = "Aditi";const price = 20;// old way — glue with + (works, but fiddly):console.log("Hi " + name + ", samosa is Rs." + price);// new way — backticks + ${ } (clean):console.log(`Hi ${name}, samosa is Rs.${price}`);both print exactly: Hi Aditi, samosa is Rs.20 — but line 6 reads like the sentence it makes. Note the backticks ` `, NOT normal quotesGreeting card
The sentence is built in script.js — see the Console.
PLAIN HTML — NO CSS AND NO SCRIPT YET${ } — byte-for-byte the same output, half the punctuationWatch it build — type your own name and price
Type into the two boxes; the code and the finished sentence update live. This is exactly what ${ } does inside a real program.
Declare a const for a dish's price, then log a sentence with a template literal.
A tiny, complete task that uses everything from today: choose the right keyword, pick the right data type, and build a sentence with ${ }. Attempt it in your own script.js, then open the solution.
Paneer Roll costs Rs.60 using variables and a template literal.- build the host page too — plain HTML first, then a little CSS, then the script (JavaScript cannot run without a page)
- the dish name and the price should never change — pick the right keyword
- the price is a number, not text — no quotes on it
- build the sentence with backticks and
${ }, not+
fswd-practice\Class-14\: activity.html (with a <style> block and a <script src="script.js"> line) and script.js.Write your three lines first. Even a wrong attempt teaches more than reading the answer cold.
<!-- FILE 1 of 3 · activity.html — plain HTML first, exactly as the rules asked --><!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Class 14 activity</title></head><body> <h1>Paneer Roll</h1> <p class="tip">Press F12 → Console for the built sentence.</p></body></html>/* HTML complete & PLAIN above. FILE 2 of 3 · the CSS — one rule per press ↓ */ <style> body { font-family: Georgia, serif; padding: 18px; } h1 { color: #C2410C; font-size: 20px; } .tip { color: #64748B; font-size: 13px; } </style><!-- CSS done. Hire the passenger — last line before </body> --> <script src="script.js"></script>// ————— FILE 3 of 3 · script.js — the three lines the task asked for —————const dish = "Paneer Roll"; // string, fixed → constconst price = 60; // number, fixed → const, no quotesconsole.log(`${dish} costs Rs.${price}`);both values are fixed, so const is correct for both. price has no quotes because it is a number. the backticks + ${ } build the sentence cleanlyPaneer Roll
Press F12 → Console for the built sentence.
PLAIN HTML — NO CSS AND NO SCRIPT YETscript.js is spelled exactly right and sits in the same folder.A quick preview, a common trap, and one legacy oddity
Truthy/falsy, the const trap — and the with statement the exam still asks about.
Three short pieces to close the concept work. First a self-study preview of truthy/falsy (fully used at Class 20). Then the single most common beginner error — reassigning a const. Then the with statement: a legacy feature you read, never write.
Every value in JavaScript, when checked in an if, counts as either truthy (treated as true) or falsy (treated as false). There are only six falsy values — everything else is truthy. You'll use this heavily for form validation in Class 20; for now, just meet them. Click each value into the bin you think it belongs in.
TRUTHY (acts as true)
FALSY (acts as false)
"0" and "false" are non-empty strings, so they're truthy!The #1 beginner error — changing a const
You will hit this in your first hour. You declare a price as const, then later try to change it — and the whole program stops. Read the real error message; it tells you exactly what happened.
script.js:2
NEW TOPIC — the with statement (read it, never write it). with(obj){ … } is a legacy feature that lets you drop an object's name inside a block and reach its properties directly — e.g. inside with(student){ … } you could write name instead of student.name. Every modern style guide (and this course) says do not write this — it's confusing and disabled in strict mode. But older code and some exam questions still use it, so you must be able to read one and say what it does. It's a scope-bending tool from the same family as var's leak you saw in Part 3.
Worked trace — why the alert shows 1, not 10
This is the exact past-paper program (P3·Q4). Step it with the button: the tracer highlights the running line, shows what's in each scope, and resolves the lookup the way JavaScript actually does it.
OUTER SCOPE
with(obj) — obj's properties
1
predict + explainQ4. Give the output and explain: var x=5, y=1; var obj={x:10}; with(obj){ alert(y); } (2 M)
with(obj) only redirects lookups for names that exist on obj. obj has x (=10) but no y.alert(y) can't find y on obj — it falls through to the outer scope, where y = 1.alert(x), it would show 10 — because x does exist on obj.)Wrap-up & the bridge to Class 15
You gave your page a memory. Next class, that memory gets structure.
Today the page learned to hold single values in labelled boxes — and to know what kind of value each box holds. But real data comes in bundles: a dish has a name and a price and a stock flag, all together. Class 15 introduces the object — one box that holds many labelled values at once. Everything you learned today is the foundation for it.
poshtik-campus\ project during the labs, where the continuous build is what actually gets committed.Take-home kit — the variable cheat-card
Copy this into your notes. It answers every variable/data-type exam question you saw today in a single glance.
- const first, let when it changes, never var. const = fixed, let = changeable, both block-scoped.
- Five types: string (quotes), number (incl. decimals), boolean (true/false), undefined (forgotten), null (chosen-empty).
- typeof value → returns a string naming the type. (Quirk:
typeof null→ "object".) - Template literal:
`Hi ${name}`— backticks, drop variables in with${ }. - with(obj){…} — legacy, read-only. Redirects only names that exist on obj; others fall through to the outer scope (that's why P3·Q4 alerts 1).
- Which keyword for a price that never changes? For a running score? Which do we never use?
- Name four data types with a one-word example each.
- What does
typeof "20"return — and why isn't it "number"? - Rewrite
"Hi " + nameas a template literal. - In
var x=5,y=1; var obj={x:10}; with(obj){ alert(y); }— what does it alert, and why?