Lesson 4: Adding Behavior to Your Webpages
From static pages to dynamic experiences
Content & Structure
"What should be on the page?"
Appearance & Style
"How should it look?"
Behavior & Interaction
"What should it do?"
JavaScript makes websites interactive and dynamic
JavaScript brings your webpages to life! ✨
Every interactive website uses JavaScript!
Three ways to include JavaScript in your webpage:
<script> console.log("Hello, World!"); </script>
<script src="script.js"></script>
Add this to your HTML file, just before the closing </body> tag:
<script> console.log("Hello from JavaScript!"); console.log("My first JavaScript program!"); </script> </body>
To see the output: Open your webpage, press F12, and look at the "Console" tab!
The console is your JavaScript playground:
Variables are containers that store information
let playerName = "Alex"; let score = 100; let isGameOver = false; console.log(playerName); // Prints: Alex console.log(score); // Prints: 100
Think of variables like labeled boxes where you can store different things!
// Step 1: Declare a variable let myName; // Step 2: Assign a value myName = "Sarah"; // Or do both at once: let age = 16; let favoriteColor = "blue";
JavaScript can store different kinds of information:
"Hello" "JavaScript" "123"
Text and characters
42 3.14 -17
Integers and decimals
true false
True or false only
[1, 2, 3] ["apple", "banana", "cherry"]
Lists of values, stored in order
{ name: "Alice", age: 15 }
Collections of key-value pairs
null
No value (empty on purpose)
undefined
A variable that hasn't been given a value yet
These types help you organize and work with all kinds of information in your programs!
userName totalScore isLoggedIn playerAge favoriteFood
x data thing 123name my-score
Add this JavaScript to your webpage:
let firstName = "Your Name Here"; let age = 16; let hobby = "coding"; console.log("Hello, my name is", firstName); console.log("I am", age, "years old"); console.log("I love", hobby); // Try changing the values and refresh!
let num1 = 10; let num2 = 5; let sum = num1 + num2; // 15 let difference = num1 - num2; // 5 let product = num1 * num2; // 50 let quotient = num1 / num2; // 2 console.log("Sum:", sum); console.log("Product:", product); // You can also combine strings! let greeting = "Hello" + " World"; // "Hello World"
Combine HTML, CSS, and JavaScript:
// Add this JavaScript to your webpage let name = "Alice"; let currentYear = 2025; let birthYear = 2010; let age = currentYear - birthYear; console.log("=== Personal Info ==="); console.log("Name:", name); console.log("Age:", age); console.log("In 10 years, I'll be:", age + 10);
Open the console to see your program work!
Create a webpage that uses HTML, CSS, and JavaScript to display information about yourself!
⭐ Be creative! Try different variable types (numbers, strings, booleans, arrays) and have fun experimenting.