JavaScript Deep Dive — The Brain
JavaScript (JS) makes pages interactive and dynamic.
- HTML = structure
- CSS = appearance
- JS = behavior
Without JS: Static pages that just display content
With JS: Dynamic apps that respond to users
Variables: Storing Data
Variables are named containers for storing information.
JavaScript
const name = "Alex"; // CONSTANT - cannot be changedlet age = 25; // VARIABLE - can be changedvar old = "legacy"; // OLD WAY - avoid usingKeyword
Changes?
const
No
let
Yes
var
Yes
Rule of Thumb
Use const by default, let only when you need to change the value.
Data Types
String (Text)
JavaScript
const greeting = "Hello, World!";const name = 'Alex'; // Single quotes work tooconst template = `Hello, ${name}`; // Template literal (backticks)Number
JavaScript
const count = 42;const price = 19.99;const negative = -10;Boolean (True/False)
JavaScript
const isLoggedIn = true;const hasError = false;Array (List)
JavaScript
const fruits = ["apple", "banana", "orange"]; // Access by index (starts at 0)fruits[0]; // "apple"fruits[1]; // "banana"fruits.length; // 3Object (Collection of Properties)
JavaScript
const person = { name: "Alex", age: 25, isStudent: true}; // Access propertiesperson.name; // "Alex"person["age"]; // 25Null and Undefined
JavaScript
let nothing = null; // Intentionally emptylet notDefined; // undefined (no value assigned)Functions: Reusable Actions
Functions are blocks of code that perform tasks.
Function Declaration
JavaScript
function greet(name) { return "Hello, " + name + "!";} // Using the functiongreet("Alex"); // Returns: "Hello, Alex!"Arrow Function (Modern Way)
JavaScript
const greet = (name) => { return "Hello, " + name + "!";}; // Short version (for simple returns)const greet = (name) => "Hello, " + name + "!";Function with Multiple Parameters
JavaScript
function add(a, b) { return a + b;} add(5, 3); // Returns: 8Conditionals: Making Decisions
If/Else Statement
JavaScript
const age = 18; if (age >= 18) { console.log("Adult");} else { console.log("Minor");}If/Else If/Else
JavaScript
const score = 85; if (score >= 90) { console.log("A grade");} else if (score >= 80) { console.log("B grade");} else if (score >= 70) { console.log("C grade");} else { console.log("Need improvement");}Comparison Operators
Operator
Meaning
===
Equal to (strict)
!==
Not equal to
>
Greater than
<
Less than
>=
Greater or equal
<=
Less or equal
Logical Operators
JavaScript
// AND - both must be trueif (age >= 18 && hasID) { console.log("Can enter");} // OR - at least one must be trueif (isAdmin || isModerator) { console.log("Has permissions");} // NOT - reverses booleanif (!isLoggedIn) { console.log("Please log in");}Loops: Repetition
For Loop
JavaScript
for (let i = 0; i < 5; i++) { console.log(i);}// Output: 0, 1, 2, 3, 4Breakdown:
let i = 0— Start at 0i < 5— Continue while i is less than 5i++— Increase i by 1 each time
For...of Loop (Arrays)
JavaScript
const fruits = ["apple", "banana", "orange"]; for (const fruit of fruits) { console.log(fruit);}// Output: apple, banana, orangeforEach Method
JavaScript
const numbers = [1, 2, 3]; numbers.forEach(num => console.log(num * 2));// Output: 2, 4, 6DOM Manipulation: Changing the Page
The DOM (Document Object Model) is how JavaScript sees and manipulates HTML.
Selecting Elements
JavaScript
// By ID (returns one element)const header = document.getElementById("main-header"); // Modern way - querySelectorconst firstCard = document.querySelector(".card"); // First matchconst allCards = document.querySelectorAll(".card"); // All matchesconst navLink = document.querySelector("nav a"); // First <a> in <nav>Changing Content
JavaScript
const title = document.querySelector("h1"); // Change texttitle.textContent = "New Title"; // Change HTMLtitle.innerHTML = "<span>New</span> Title";Changing Styles
JavaScript
const box = document.querySelector(".box"); box.style.color = "blue";box.style.backgroundColor = "white";box.style.fontSize = "20px";Changing Classes
JavaScript
const element = document.querySelector(".card"); element.classList.add("active"); // Add classelement.classList.remove("active"); // Remove classelement.classList.toggle("active"); // Toggle on/offelement.classList.contains("active"); // Check if has classEvent Handling: Responding to Users
Events are actions users take (clicks, typing, scrolling).
addEventListener Method
JavaScript
const button = document.querySelector("button"); button.addEventListener("click", () => { alert("Button was clicked!");});Common Events
Event
Triggers When
click
Element is clicked
submit
Form is submitted
input
Input value changes
keydown
Key is pressed
mouseover
Mouse enters element
load
Page finishes loading
Example: Form Handling
JavaScript
const form = document.querySelector("form");const input = document.querySelector("input"); form.addEventListener("submit", function(event) { event.preventDefault(); // Stop page refresh console.log("Input value:", input.value);});Putting It Together
JavaScript
// Counter App Logic // Get elementsconst countDisplay = document.getElementById("count");const incrementBtn = document.getElementById("increment");const decrementBtn = document.getElementById("decrement"); // Initialize counterlet count = 0; // Update display functionfunction updateDisplay() { countDisplay.textContent = count; // Change color based on value if (count > 0) { countDisplay.style.color = "green"; } else if (count < 0) { countDisplay.style.color = "red"; } else { countDisplay.style.color = "black"; }} // Event listenersincrementBtn.addEventListener("click", () => { count++; updateDisplay();}); decrementBtn.addEventListener("click", () => { count--; updateDisplay();});Lesson Summary
Variables
constfor constants,letfor changeable values
Data Types
- String, Number, Boolean, Array, Object, null, undefined
Functions
JavaScript
function name(params) { return value; }const name = (params) => value;Conditionals
JavaScript
if (condition) { } else if (condition) { } else { }Loops
JavaScript
for (let i = 0; i < n; i++) { }for (const item of array) { }array.forEach(item => { });DOM
- Select:
document.querySelector() - Modify:
.textContent,.innerHTML,.style - Classes:
.classList.add/remove/toggle()
Events
JavaScript
element.addEventListener("event", () => { });📝 Quiz
1/4When should you use 'const' vs 'let'?
Next Up
Lesson 2.5: Browser DevTools
Learn to use the most powerful debugging tool available!