Unit 5: JavaScript Basics & Control Flow
Interactive Code Execution Environment
You should be comfortable with HTML structure (Unit 2). JavaScript manipulates the DOM, so knowing <div>, <p>, <button>, and <input> elements is essential. Review Unit 2 if needed.
- Declare variables using let/const and work with JavaScript primitives (string, number, boolean)
- Write if/else if/else and switch statements to control program flow
- Predict type coercion outcomes and use strict equality (===) correctly
- Implement for, while, and do-while loops with break and continue
1. The Building Blocks: Data Types & Operators
JavaScript is a client-side scripting language. This means the code runs directly on the user's hardware (in the browser), not on the university's web server. It provides the "behavior" to HTML's "structure."
- Variables: Containers for storing data values (
let,const,var). - Data Types: JS is dynamically typed. The main primitives are:
String("Hello"),Number(42 or 3.14),Boolean(true/false), andUndefined(a variable declared but not assigned). - Type Conversion: JS can implicitly coerce types (e.g.,
"5" + 2results in the string"52", but"5" - 2results in the number3). Explicit conversion usesNumber("5")orString(5).
var vs let
var is function-scoped and hoisted; let is block-scoped. Using var inside a loop creates one shared variable, while let creates a new binding per iteration. Always prefer let (or const) over var.
| Operator Type | Examples | Precedence / Purpose |
|---|---|---|
| Arithmetic | +, -, *, /, % (Modulus) | Math operations. * and / execute before + and - (BODMAS rule). |
| Comparison | ==, ===, >, <=, != | Returns a Boolean. Always use === (strict equality) as it checks both value AND data type. |
| Logical | && (AND), || (OR), ! (NOT) | Used to combine multiple conditions in a control flow statement. |
2. Control Flow: Conditional Statements
(). If it resolves to true, the code block inside the braces {} executes.
If / Else If / Else Visualizer
Execution Engine State
let marks = 75;
let grade;
if (marks >= 80) {
grade = 'A';
} else if (marks >= 60) {
grade = 'B';
} else if (marks >= 40) {
grade = 'C';
} else {
grade = 'F';
}
console.log("Grade:", grade);
3. Switch Statement — Multi-Way Branching
The switch statement evaluates an expression and executes code blocks matching the case value. It is cleaner than multiple if/else if chains when comparing a single value against many possibilities.
Each case ends with break to prevent "fall-through" (execution continuing to the next case). Without break, all subsequent cases execute until a break or end of switch.
Day-of-Week Switch Tester
Execution State
let day = 3;
let dayName;
switch (day) {
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
case 4:
dayName = "Thursday";
break;
case 5:
dayName = "Friday";
break;
case 6:
dayName = "Saturday";
break;
case 7:
dayName = "Sunday";
break;
default:
dayName = "Invalid day";
}
console.log(dayName);
4. Type Coercion & Operator Precedence
Type coercion is JavaScript's automatic conversion of one data type to another. Understanding it prevents bugs.
== vs ===
Always use === (strict equality). The loose == coerces types, causing 0 == false to be true and "" == 0 to be true. This is a leading source of bugs in student code.
break in Switch
Without break, execution "falls through" to the next case. If day = 3 and case 3 has no break, it executes case 4, 5, 6, and 7 as well. Always end each case with break;
() Grouping → ! NOT → * / % Multiply/Divide/Mod → + - Add/Subtract → < > <= >= Comparison → === !== == != Equality → && AND → || OR → = Assignment
5. Iteration: Loops (For, While, Do-While)
- A
for loop is used when you know exactly how many times to iterate. It contains three parts: initialization, condition, and increment.
- A
while loop is used when you want to iterate as long as a condition remains true, usually when the total number of iterations is unknown beforehand.
-
break immediately exits the entire loop. continue skips the current iteration and jumps to the next one.
For Loop Step Simulator
Click step to execute the loop cycle one phase at a time.
Engine State
do { /* code */ } while (condition);
// For loop (known iterations)
for (let i = 0; i < 3; i++) {
console.log("Iteration: " + i);
}
// While loop (condition-based)
let j = 0;
while (j < 3) {
console.log("While iteration: " + j);
j++;
}
6. Data Types & the typeof Operator
JavaScript is dynamically typed — a variable's type is decided at runtime. The typeof operator reveals a value's category. Type a JS value (try 42, "hi", true, null, [1,2], {a:1}, function(){}) and inspect it.
Note: typeof null is the quirk "object", and typeof [] is also "object".
7. Operators & Precedence
Operators follow a precedence order: * / % evaluate before + -, which evaluate before comparisons, then &&, then ||. Pick two operands and an operator, or type a full expression, to see the result and its type.
Prefer ===; == coerces (5 == "5" is true).
8. Truthy, Falsy & Type Coercion
In a boolean context, only false, 0, "", null, undefined, and NaN are falsy; everything else is truthy. == coerces types; === doesn't. Click a tricky value or type your own.
9. while vs do-while
A while loop checks the condition before each iteration and may run zero times. A do-while checks after, so it always runs at least once — even if the condition is already false. Set a start that fails the condition and compare.
Try kind = while, start = 5, limit = 3 → nothing prints. Switch to do-while → one iteration prints.
10. break & continue in Loops
break exits the loop entirely; continue skips the rest of the current iteration and jumps to the next. Toggle them over the numbers 1–5 and watch which iterations run.
Hoisting
JavaScript moves variable and function declarations to the top of their scope before execution. var declarations are hoisted (value = undefined), let/const are hoisted but not initialized (Temporal Dead Zone):
console.log(x); // undefined (var hoisted, not assigned) var x = 5; console.log(y); // ReferenceError: Cannot access before initialization let y = 5;
Function declarations are fully hoisted — you can call them before the definition line:
greet(); // "Hello!" — works
function greet() { console.log("Hello!"); }Function expressions are NOT hoisted (they follow variable hoisting rules).
Closures
A closure is created when a function retains access to its outer (enclosing) scope even after the outer function has returned. This is one of JavaScript's most powerful features:
function createCounter() {
let count = 0;
return function() {
count++;
return count;
};
}
const counter = createCounter();
console.log(counter()); // 1
console.log(counter()); // 2
console.log(counter()); // 3The inner function "closes over" the count variable — it persists in memory as long as counter exists. This enables data encapsulation, factory functions, and callback state preservation.
IIFE — Immediately Invoked Function Expression
An IIFE runs as soon as it is defined. Used historically to create private scope before let/const:
(function() {
var privateVar = "secret";
// This var is not accessible outside
})();