Introduction to JavaScript
JavaScript is what makes pages interactive! Let's start your programming journey.
What JavaScript Does
- Responds to clicks
- Validates forms
- Creates animations
- Loads data without reloading
- Practically everything interactive
Where to Write JavaScript
1. In HTML (tag script)
html
<body> <h1>My Page</h1> <script> alert("Hello, World!"); </script></body>2. External file (recommended)
html
<body> <h1>My Page</h1> <script src="script.js"></script></body>javascript
// script.jsalert("Hello, World!");Important: Put <script> at the end of body so HTML loads first!
Console: Your Best Friend
Open the browser (F12 → Console) and type:
javascript
console.log("Hello!");console.log() shows messages in the console. Super useful for testing!
Comments
javascript
// Single-line comment /* Multi-line comment*/Your First Program
Create script.js:
javascript
// Show message in consoleconsole.log("Script is running!"); // Variableslet name = "Maria";let age = 25; // Show variablesconsole.log("Name:", name);console.log("Age:", age); // Calculationlet birthYear = 2026 - age;console.log("Birth year:", birthYear);Open the page and check the console!
Interacting with the User
alert - Show message
javascript
alert("Welcome to my site!");confirm - Yes/No question
javascript
let answer = confirm("Do you want to continue?");console.log(answer); // true or falseprompt - Get input
javascript
let name = prompt("What's your name?");console.log("Hello, " + name);Practice: Interactive Greeting
javascript
// Get namelet name = prompt("What's your name?"); // Get agelet age = prompt("How old are you?"); // Show greetinglet message = "Hello, " + name + "! You are " + age + " years old.";alert(message); // Calculate year bornlet yearBorn = 2026 - age;console.log(name + " was born around " + yearBorn);Template Literals (Modern)
Instead of concatenating with +, use backticks:
javascript
let name = "Maria";let age = 25; // Old (concatenation)let msg1 = "Hello, " + name + "! You are " + age + " years old."; // Modern (template literal)let msg2 = `Hello, ${name}! You are ${age} years old.`;Much easier to read!
Summary
- ✅ JavaScript adds interactivity
- ✅
console.log()to debug - ✅
alert,confirm,promptfor interaction - ✅ Template literals with backticks
``
In the next lesson, we'll dive deep into variables and types! 🚀