Free tutorials & notes in Hindi & English · Clean code examples 🧰 Free PDF & Image Tools →
🟨 Days 1–7 – JavaScript Fundamentals  ·  Day 02

Day 2: Variables, Data Types & Template Literals

⏱ 80 min📶 Beginner🎯 100% self-study
Day 2 / 30

✅ 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

JavaScript
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.
Sharma Sweets cart: 3
KeywordRe-assign?ScopeUse
const ⭐NoBlock { }Default choice – most values never change
letYesBlock { }Counters, totals, values that change
varYesFunction (leaks out of blocks)Old code only – avoid in new code
💡 Rule of thumb

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

JavaScript
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));
string number boolean undefined object bigint object object true
🧠 Two famous quirks

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

JavaScript
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'));
Wrong: 2900 Wrong: 1800 Right: 1800 2.5 0 NaN 250 1.5 1800 1800 false true
FunctionExampleResult
Number()Number('2.5')2.5 (NaN if not a number)
parseInt / parseFloatparseInt('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

JavaScript
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);
Hi Aarti, 2 kg Kaju Katli = Rs 1800 Hi Aarti, 2 kg Kaju Katli = ₹1800 Sharma Sweets 🍬 Order confirmed for Aarti. Total: ₹1800

Real task: a bill calculator

HTML + JavaScript
<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>
▶  Change the quantity and calculate

🏅 Job skills unlocked today

✔ Choose const or let correctly✔ Name variables clearly in camelCase✔ Identify data types with typeof✔ Convert input strings to numbers and build messages with template literals

Practice tasks

🏋️ Practice – do it yourself

Task 1: Store a student’s name, marks in 3 subjects (out of 100) and print the total and percentage with a template literal.
Show solution
JavaScript
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)}%`);
Riya: 259/300 = 86.3%
Task 2: Predict, then run: "5" + 3, "5" - 3, "5" * "2", true + 1.
Show solution
JavaScript
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)
53 2 10 2
Task 3: Make a “EMI preview” that reads a loan amount and months from inputs and shows amount ÷ months (no interest yet).

Quick quiz

🧠 Quick Quiz – test yourself

1. Which keyword should be your default?
Use let only when re-assigning.
2. Value of '10' + 5?
String concatenation.
3. typeof null is…
Historic bug.
4. Values from an <input> are…
Convert with Number().
5. Template literals use…
Backtick key is left of 1.

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}`.
➡️ Next

Day 3: operators and conditions – discounts, free delivery rules and grade calculators with if, else and switch.

Frequently Asked Questions

Can a const array be changed?
Yes – you cannot re-assign the variable, but you can push items into the array or change object properties. Day 7 shows how to make copies instead.
Why does 0.1 + 0.2 give 0.30000000000000004?
Numbers are stored in binary floating point. For money, work in paise (integers) or round with toFixed(2) for display – Day 9 covers this.
← JavaScript (30 Days)
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

Next topicDay 3: Operators, Conditions & Decisions Your progress: 2 / 30 (7%) · Lesson 3 / 30 Continue →

How was this lesson?

Your feedback helps us make the content better.

Write a review or suggestion (optional)

After approval, your name and city may appear publicly with your review. Please do not write your email or phone number.

▶ CodingEasily on YouTube

Learn with video lessons in easy Hindi

Featured video: RDBMS Part 3 – Class XI Commerce IT

▶ Subscribe – it’s free