Chapter 2 — JS Variables & Operators
📚 Chapter Overview
Before making a page dynamic, you must understand how JavaScript stores and manipulates data. In this chapter, you will learn the difference between let, const, and var, and how to perform calculations.
Learning Objectives:
- Understand Block Scope vs Global Scope.
- Master Arithmetic and Comparison operators.
- Perform basic Template Literals for string output.
2.1 Variables (let, const, var)
Part 1 — Definition
Variables are containers for storing data values. Modern JavaScript uses let for variables that can change and const for values that stay the same. var is an older way and is generally avoided in modern development.
Part 2 — Syntax
let score = 0;
const pi = 3.14;
var name = "John"; // Avoid in modern JS
Part 3 — Example
Problem: Keep track of a user's login status.
const userName = "Alice";
let isLoggedIn = false;
// After login
isLoggedIn = true;
console.log(userName + " is logged in: " + isLoggedIn);
Part 4 — Video
Video: Coming Soon
2.2 Arithmetic and Template Literals
Part 1 — Definition
JavaScript supports standard math operators (+, -, *, /). Template Literals (using backticks ``) allow you to embed variables directly into strings using ${variable}, which is much cleaner than string concatenation.
Part 2 — Syntax
let total = a + b;
console.log(`The sum is ${total}`);
Part 3 — Example
Problem: Calculate the total price including tax.
let price = 100;
let tax = 0.05;
let finalPrice = price + (price * tax);
console.log(`Total Price: $${finalPrice}`);
Output: Total Price: $105
Part 4 — Video
Video: Coming Soon
🏆 Chapter Challenge
Challenge Objective
Build a "Simple BMI Calculator" using JavaScript variables and math.
Requirements
- Store weight (kg) and height (m) in variables.
- Calculate BMI = weight / (height * height).
- Log the result in the console using a Template Literal.
Step-by-Step Process
- Use
letfor weight and height. - Apply the math formula.
- Output the message: "Your BMI is [value]".
Expected Deliverables
bmi.jsor internal script intest.html.