← BEUVAULT 100219 Course U1 U2 U3 U4 U5 U6

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

Theory & Concepts:

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), and Undefined (a variable declared but not assigned).
  • Type Conversion: JS can implicitly coerce types (e.g., "5" + 2 results in the string "52", but "5" - 2 results in the number 3). Explicit conversion uses Number("5") or String(5).
⚠ Common Pitfall: 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 TypeExamplesPrecedence / 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

Theory: Conditionals allow a program to take different paths based on runtime data. The engine evaluates the condition inside the parentheses (). If it resolves to true, the code block inside the braces {} executes.

If / Else If / Else Visualizer

if (marks >= 90) {
grade = 'A+';
} else if (marks >= 70) {
grade = 'A';
} else {
grade = 'B';
}

Execution Engine State

RAM (Memory Variables)
marks: undefined
grade: undefined
Console Output
> Waiting for execution...
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

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;
}

Execution State

day (input): 3
dayName (result):
Console Output
> Press "Run Switch" to execute.
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.

⚠ Common Pitfall: == 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.

⚠ Common Pitfall: Missing 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;

"5" + 2
"52" (String)
The + operator with a string triggers string concatenation.
"5" - 2
3 (Number)
The - operator converts strings to numbers.
"5" * "3"
15 (Number)
Both strings coerced to numbers for multiplication.
!"hello"
false (Boolean)
Non-empty strings are truthy, so !"hello" is false.
0 == false
true (loose)
Loose equality coerces 0 and false to the same value.
0 === false
false (strict)
Strict equality checks type — Number !== Boolean.
Operator Precedence (highest to lowest):
() Grouping → ! NOT → * / % Multiply/Divide/Mod → + - Add/Subtract → < > <= >= Comparison → === !== == != Equality → && AND → || OR → = Assignment

5. Iteration: Loops (For, While, Do-While)

Theory: Loops prevent code repetition (DRY - Don't Repeat Yourself).
- 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.

600ms
for (let i = 0; i < 3; i++) {
console.log("Iteration: " + i);
}

Engine State

Loop Control Variable
i: undefined
Phase: Not started
do-while variant: executes body at least once before checking condition.
do { /* code */ } while (condition);
Console Output
// 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++;
}

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()); // 3

The 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
})();