Day 2: Variables, Data Types & Template Literals
✅ Today you will learn
- Store values with let and const (and why var is avoided)
- Naming rules and good names
- Data types: string, number, boolean, null, undefined, bigint, symbol, object
- typeof and converting between types
- Template literals for clean messages
🏢 In the real world
Every program remembers things: the product name, its price, how many kg the customer wants, whether delivery is free. Variables are labelled boxes for those values. A real bug from a shop’s billing page: “2 kg × ₹900 shows ₹9009002” – the quantity was stored as text. Today you learn exactly why that happens and how to prevent it.
let and const
const shopName = 'Sharma Sweets'; // will never change → const let cartItems = 0; // will change → let cartItems = cartItems + 1; cartItems = cartItems + 2; console.log(shopName, 'cart:', cartItems); // shopName = 'Other'; ← TypeError: Assignment to constant variable.
| Keyword | Re-assign? | Scope | Use |
|---|---|---|---|
| const ⭐ | No | Block { } | Default choice – most values never change |
| let | Yes | Block { } | Counters, totals, values that change |
| var | Yes | Function (leaks out of blocks) | Old code only – avoid in new code |
Start every variable with const. Change it to let only when you actually need to re-assign it. Your code becomes easier to read because readers know which values can change.
Naming variables
Bad names
- x, a1, data2
- TOTALAMOUNTOFBILL
- total-price (invalid: hyphen)
- 2ndItem (invalid: starts with a digit)
Good names (camelCase)
- pricePerKg, quantityKg
- isDeliveryFree (booleans start with is/has)
- customerName, orderTotal
- MAX_ITEMS for fixed settings
Data types
const name = 'Kaju Katli'; // string
const price = 900; // number (integers and decimals)
const rating = 4.8; // number
const inStock = true; // boolean
let discountCode; // undefined – declared, no value yet
const gstNumber = null; // null – intentionally empty
const bigOrderId = 9007199254740993n; // bigint
const product = { name, price }; // object
const sizes = ['250g', '500g', '1kg']; // array (also an object)
console.log(typeof name, typeof price, typeof inStock);
console.log(typeof discountCode, typeof gstNumber, typeof bigOrderId);
console.log(typeof product, typeof sizes, Array.isArray(sizes));typeof null is "object" – a bug from 1995 kept for compatibility. And arrays are objects too, so use Array.isArray() to check for arrays. Interviewers love both.
Converting types – the 9009002 bug
const qtyFromInput = '2'; // everything from an <input> is a STRING
const price = 900;
console.log('Wrong:', qtyFromInput + price); // joins text!
console.log('Wrong:', qtyFromInput * price); // works by luck (* converts)
console.log('Right:', Number(qtyFromInput) * price); // convert first ✅
console.log(Number('2.5'), Number(''), Number('abc'));
console.log(parseInt('250g'), parseFloat('1.5kg'));
console.log(String(1800), (1800).toString(), Boolean(0), Boolean('hi'));| Function | Example | Result |
|---|---|---|
| Number() | Number('2.5') | 2.5 (NaN if not a number) |
| parseInt / parseFloat | parseInt('250g') | 250 – reads digits until the first non-digit |
| String() | String(1800) | '1800' |
| Boolean() | Boolean('') | false – empty string, 0, null, undefined, NaN are falsy |
| Number.isNaN() | Number.isNaN(Number("abc")) | true – check before using a number |
Template literals
const customer = 'Aarti';
const item = 'Kaju Katli';
const qty = 2;
const price = 900;
// Old way – hard to read
console.log('Hi ' + customer + ', ' + qty + ' kg ' + item + ' = Rs ' + qty * price);
// Template literal – backticks and ${ }
console.log(`Hi ${customer}, ${qty} kg ${item} = ₹${qty * price}`);
// Multi-line text is easy too
const sms = `Sharma Sweets 🍬
Order confirmed for ${customer}.
Total: ₹${qty * price}`;
console.log(sms);Real task: a bill calculator
<label>Quantity (kg) <input id="qty" type="number" value="2" min="0.25" step="0.25"></label>
<button id="calc">Calculate</button>
<pre id="bill"></pre>
<script>
const PRICE_PER_KG = 900;
const GST_RATE = 0.05; // 5% GST on sweets
document.querySelector('#calc').addEventListener('click', function () {
const qty = Number(document.querySelector('#qty').value); // string → number
const amount = qty * PRICE_PER_KG;
const gst = amount * GST_RATE;
const total = amount + gst;
document.querySelector('#bill').textContent =
`Kaju Katli ${qty} kg × ₹${PRICE_PER_KG}
Amount ₹${amount.toFixed(2)}
GST 5% ₹${gst.toFixed(2)}
Total ₹${total.toFixed(2)}`;
});
</script>🏅 Job skills unlocked today
Practice tasks
🏋️ Practice – do it yourself
Show solution
const student = 'Riya';
const maths = 88, science = 92, english = 79;
const total = maths + science + english;
const percent = (total / 300) * 100;
console.log(`${student}: ${total}/300 = ${percent.toFixed(1)}%`);"5" + 3, "5" - 3, "5" * "2", true + 1.Show solution
console.log("5" + 3); // "53" (+ with a string joins)
console.log("5" - 3); // 2 (- converts to number)
console.log("5" * "2"); // 10
console.log(true + 1); // 2 (true becomes 1)Quick quiz
🧠 Quick Quiz – test yourself
Interview corner
💼 Interview Corner
Difference between let, const and var?
var is function-scoped, hoisted with undefined and can be re-declared; let and const are block-scoped and in the temporal dead zone until declared. const cannot be re-assigned (but an object it points to can still be mutated).
null vs undefined?
undefined means a variable exists but has no value yet (set by JavaScript); null is an intentional “no value” set by the programmer. typeof undefined is "undefined", typeof null is "object"; null == undefined is true but null === undefined is false.
Summary
- const by default, let when re-assigning, avoid var.
- camelCase, meaningful names; booleans start with is/has.
- typeof shows the type; inputs are strings – convert with Number().
- Template literals: `Total ₹${total}`.
Day 3: operators and conditions – discounts, free delivery rules and grade calculators with if, else and switch.
