1 WEB FOUNDATIONS

JavaScript Fundamentals

🟨 JavaScript Fundamentals: The Language of the Web

HTML is the skeleton. CSS is the skin. JavaScript is the brain/muscle system. It is the only programming language natively understood by every web browser on Earth. Without JS, a website is just a static magazine page. With JS, it becomes a living, breathing application.

In this lesson, we cover the core building blocks of the language: variables, data types, logic, and functions.


1️⃣ Variables: How Programs Remember Things

A program constantly takes in data, modifies it, and spits it back out. If it cannot remember the data for more than a millisecond, it is useless. Variables are labeled boxes where we store data in the computer's RAM.

// ❌ The old, broken way (Pre-2015). Never use 'var' again.
var speed = 100;

// ✅ The modern way for values that WILL change (Mutable)
let score = 0;
score = score + 10; // score is now 10

// ✅ The modern way for values that WILL NOT change (Immutable)
const PI = 3.14159;
PI = 4; // 💥 ERROR: Uncaught TypeError: Assignment to constant variable.

The Professional Rule: Always use const by default. Only downgrade to let if you mathematically prove to yourself that the variable must change (like a counter in a loop). This prevents hundreds of accidental bug mutations.


2️⃣ Data Types: What Can Fit in the Box?

JavaScript is "Dynamically Typed". An int in Java can only ever hold a number. In JS, a variable can hold a number right now, and seamlessly hold a word one second later.

Primitive Types (Single, simple values)

  1. String: Text wrapped in quotes. const name = "Mwero";
  2. Number: Decimals or integers. const age = 25; const price = 9.99;
  3. Boolean: True or False. const isLoggedIn = true;
  4. Undefined: The default state of an empty box. let password; console.log(password); // undefined
  5. Null: The explicit declaration of nothing. const activeUser = null;

Reference Types (Complex structures)

Complex data types don't store the actual data in the variable; they store a memory address pointing to where the data lives.

1. Arrays (Ordered Lists):

const colors = ["red", "green", "blue"];
console.log(colors[0]); // "red"
colors.push("yellow");  // Adds to the end of the list

2. Objects (Key-Value Dictionaries):

const user = {
    firstName: "Mwero",
    role: "Admin",
    isActive: true
};
console.log(user.firstName); // Dot notation -> "Mwero"
console.log(user["role"]);    // Bracket notation -> "Admin"

3️⃣ Logic and Control Flow (if and else)

Programs must make decisions. Control flow statements are the forks in the road.

const userAge = 20;

if (userAge >= 18) {
    console.log("Welcome to the casino.");
} else if (userAge === 17) {
    console.log("Come back next year.");
} else {
    console.log("Access denied by security.");
}

The Double Equals vs. Triple Equals Trap

This is the most common bug for beginners migrating from other languages.

  • == (Loose Equality): JavaScript attempts to violently convert the types to force a match. "5" == 5 is true. This causes massive, silent bugs in finance apps.
  • === (Strict Equality): Checks both the value and the type. "5" === 5 is false.

The Professional Standard: Never use ==. Always, exclusively use ===.


4️⃣ Functions: Reusable Machines

If you find yourself copying and pasting the exact same 10 lines of code three times, your code is unmaintainable. A Function is a mini-machine: it takes raw materials (Arguments), processes them, and outputs a finished product (Return).

Anatomy of a Classic Function

// 1. Definition (Building the machine)
function calculateTotal(price, taxRate) {
    // The "return" statement ejects the final value OUT of the machine
    return price + (price * taxRate);
}

// 2. Execution (Plugging it in and running it)
const finalBill = calculateTotal(100, 0.08); // Returns 108
console.log(finalBill);

The Scope Problem (Local vs Global)

Variables created inside a machine cannot be accessed outside the machine.

const globalTax = 0.08; // Accessible everywhere

function doMath() {
    const localSecret = "I am hidden"; // Only exists between these brackets { }
    return 100 * globalTax;
}

console.log(localSecret); // 💥 ReferenceError: localSecret is not defined

5️⃣ Loops (Repetition at Scale)

If you need to print 1,000 emails, you don't write console.log() one thousand times. You write it once and loop it.

The Classic for Loop

Perfect for when you know exactly how many times the loop should run.

// 1. Initial State (let i = 0); 
// 2. The Condition required to keep running (i < 5); 
// 3. What to do after each lap (i++)
for (let i = 0; i < 5; i++) {
    console.log("Lap number: " + i);
}
// Outputs 0, 1, 2, 3, 4

Loop Over an Array (Modern Approach)

Modern JS provides beautiful methods to loop over arrays without tracking an i index manually.

const students = ["Alice", "Bob", "Charlie"];

// For the 'students' array, grab 'student' one by one, and run this function block
students.forEach(function(student) {
    console.log("Graduating today: " + student);
});

💡 Summary Comparison

ConceptThe Wrong WayThe Professional Way
Variable Declarationvar score = 10;const score = 10; (Or let if mutable)
Equality Checksif (age == "18")if (age === 18)
Code DuplicationCopy-pasting 5 lines of logicWrapping those 5 lines into a function
Mental ModelFunctions just "do things".Functions take arguments and return predictable results.

Knowledge Check

Complete this quick quiz to verify your understanding and unlock the next module.