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

FunctionReturnsUX note
prompt(message, default?)string or null (Cancel)Blocks page — fine for learning, rare in production
alert(message)undefinedBlocks — use sparingly
confirm(message)true / falseBlocks — 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

  1. prompt gives strings — convert before arithmetic.
  2. alert / confirm are synchronous and blocking — great for learning, not for modern UX.
  3. Combine variables, if, and template literals for readable mini programs.

Explain-It Challenge

Explain without notes:

  1. Why does prompt("Age") + 5 often produce nonsense without Number()?
  2. What does prompt return when the user clicks Cancel?
  3. Name one reason production apps avoid alert for normal output.

Navigation: ← 1.13.g — Data Types · 1.13 Overview