Episode 1 — Fundamentals / 1.13 — Introduction to JavaScript
1.13.h — Mini Practice Programs
In one sentence: Small programs — a calculator, a greeting, and prompt-based input — cement variables, types, and control flow while you still have the training wheels of
alert/prompt/console.
Navigation: ← 1.13.g — Data Types · 1.13 Overview
1. Calculator (two numbers, one operation)
prompt returns a string. Convert with Number() (or parseFloat) before math.
<script>
const a = Number(prompt("First number?"));
const b = Number(prompt("Second number?"));
const op = prompt("Operation? (+, -, *, /)");
let result;
if (op === "+") result = a + b;
else if (op === "-") result = a - b;
else if (op === "*") result = a * b;
else if (op === "/") result = b !== 0 ? a / b : "Cannot divide by zero";
else result = "Unknown operator";
console.log("Result:", result);
alert("Result: " + result);
</script>
Stretch goals: Validate Number.isNaN(a) / Number.isNaN(b) and show a friendly error.
2. Greeting system
const hour = new Date().getHours();
let greeting;
if (hour < 12) greeting = "Good morning";
else if (hour < 18) greeting = "Good afternoon";
else greeting = "Good evening";
const name = prompt("What is your name?");
alert(`${greeting}, ${name}!`);
Uses template literals (backticks) for readable string interpolation.
3. prompt, alert, confirm
| Function | Returns | UX note |
|---|---|---|
prompt(message, default?) | string or null (Cancel) | Blocks page — fine for learning, rare in production |
alert(message) | undefined | Blocks — use sparingly |
confirm(message) | true / false | Blocks — simple yes/no |
Production apps use HTML forms and DOM instead of blocking dialogs — but prompts are fine for first scripts.
4. Input handling pattern
const raw = prompt("Enter your age");
const age = Number(raw);
if (raw === null) {
console.log("User cancelled");
} else if (Number.isNaN(age)) {
console.log("Not a valid number");
} else {
console.log("Next year you will be", age + 1);
}
Always handle Cancel (null) and invalid numbers.
5. Key takeaways
promptgives strings — convert before arithmetic.alert/confirmare synchronous and blocking — great for learning, not for modern UX.- Combine variables,
if, and template literals for readable mini programs.
Explain-It Challenge
Explain without notes:
- Why does
prompt("Age") + 5often produce nonsense withoutNumber()? - What does
promptreturn when the user clicks Cancel? - Name one reason production apps avoid
alertfor normal output.
Navigation: ← 1.13.g — Data Types · 1.13 Overview