JavaScript – Making Webpages Interactive!
intermediate25 XP

Functions & Conditionals – Making Decisions!

Write reusable functions and use if/else to make your code respond differently based on what the user does!

Functions & Conditionals — Code That Thinks! 🧠

Functions are reusable actions and conditionals let your code make decisions. These two together let you build almost anything!

Functions — Reusable Code Blocks

JavaScript
// Define a function
function greetPlayer(name) {
  console.log("Welcome, " + name + "! 👋");
}

// Call the function
greetPlayer("Alex");     // Welcome, Alex! 👋
greetPlayer("Sam");      // Welcome, Sam! 👋
greetPlayer("Jordan");   // Welcome, Jordan! 👋

Instead of writing the same code 3 times, you write it once as a function!

Functions with Return Values

JavaScript
function calculateScore(correct, total) {
  let percentage = (correct / total) * 100;
  return percentage;
}

let myScore = calculateScore(8, 10);
console.log(myScore);    // 80
console.log(myScore + "%");  // "80%"

Arrow Functions (Modern Style)

JavaScript
// Regular function
function double(num) {
  return num * 2;
}

// Arrow function (same thing, shorter!)
const double = (num) => num * 2;

console.log(double(5));   // 10
console.log(double(21));  // 42

Conditionals — If This, Then That

JavaScript
let score = 75;

if (score >= 90) {
  console.log("🏆 Amazing! You got an A!");
} else if (score >= 70) {
  console.log("👍 Good work! You got a B!");
} else if (score >= 50) {
  console.log("📚 Keep practising! You got a C.");
} else {
  console.log("💪 Don't give up! Try again!");
}

Comparison Operators

| Operator | Meaning | Example | |----------|---------|---------| | === | Exactly equal | 5 === 5 → true | | !== | Not equal | 5 !== 3 → true | | > | Greater than | 10 > 5 → true | | < | Less than | 3 < 7 → true | | >= | Greater or equal | 5 >= 5 → true |

Logical Operators

JavaScript
let age = 13;
let hasPermission = true;

// AND — both must be true
if (age >= 8 && age <= 16) {
  console.log("Perfect age for this app!");
}

// OR — at least one must be true
if (age < 13 || hasPermission) {
  console.log("Can access with permission");
}

// NOT — flips true/false
if (!gameOver) {
  console.log("Keep playing!");
}

🌟 Grade Calculator Function

JavaScript
function getGrade(score) {
  if (score >= 90) return "A ⭐";
  else if (score >= 80) return "B 👍";
  else if (score >= 70) return "C 📚";
  else if (score >= 60) return "D 💪";
  else return "F — retry! 🔄";
}

console.log(getGrade(95));   // A ⭐
console.log(getGrade(73));   // C 📚
console.log(getGrade(55));   // D 💪

Quick check

01/3

What keyword sends a value back from a function?