← レベル2 – ウィザード

レッスン 3/8 ⏱ 30 分

変数と条件分岐

ページに記憶させ、判断させる。プログラミングの核心。

見てみよう:変数——プログラムの記憶

変数 はラベル付きの箱——プログラムが値を保存する場所:

let clickCount = 0;        // number
let name = "Jake";         // string (text)
let isWeekend = true;      // true/false

変数で計算したり、値を変えたり:

clickCount = clickCount + 1;   // increase by 1
clickCount++;                  // same thing, shorter

見てみよう:クリックカウンター

前レッスンのボタンと変数を組み合わせよう:

<button id="counter">Clicked: 0×</button>
const counter = document.getElementById("counter");
let count = 0;

counter.addEventListener("click", () => {
  count++;
  counter.textContent = "Clicked: " + count + "×";
});

初めてページが 何かを覚える。クリックのたびに箱の数字が増えて表示される。

見てみよう:条件——判断する

条件 は:「これが真なら A を、そうでなければ B を。」

if (count >= 10) {
  counter.textContent = "Ten clicks! You've got some serious stamina 🏆";
} else {
  counter.textContent = "Clicked: " + count + "×";
}

やってみよう 💪

サプライズ付きカウンターを作ろう:一定回数クリックしたら追加の何かが起きる。

🏫 学校サイト——給食の投票
<h2>Vote for pizza day!</h2>
<button id="vote">Vote 🍕 (0 votes)</button>
<p id="result"></p>
const vote = document.getElementById("vote");
const result = document.getElementById("result");
let votes = 0;

vote.addEventListener("click", () => {
  votes++;
  vote.textContent = "Vote 🍕 (" + votes + " votes)";

  if (votes >= 5) {
    result.textContent = "Decided! Pizza day wins the election. 🏆";
  }
});
🙋 個人サイト——リフティングカウンター
<h2>How many times can I juggle the ball?</h2>
<button id="kick">Kick! (0)</button>
<p id="record"></p>
const kick = document.getElementById("kick");
const record = document.getElementById("record");
let kicks = 0;

kick.addEventListener("click", () => {
  kicks++;
  kick.textContent = "Kick! (" + kicks + ")";

  if (kicks === 20) {
    record.textContent = "20 kicks – new personal record! 🎉";
  }
});
🌍 旅行日記——訪問国カウンター
<h2>Country counter</h2>
<button id="country">Add a country (0)</button>
<p id="rating"></p>
const country = document.getElementById("country");
const rating = document.getElementById("rating");
let countryCount = 0;

country.addEventListener("click", () => {
  countryCount++;
  country.textContent = "Add a country (" + countryCount + ")";

  if (countryCount >= 10) {
    rating.textContent = "Ten countries – you're a globetrotter! 🌍";
  } else if (countryCount >= 5) {
    rating.textContent = "Five countries – beginner traveler. 🎒";
  }
});

else if に注目——複数の条件をつなげる方法。

⚽ クラブサイト——得点トラッカー
<h2>Shooting practice</h2>
<button id="goal">GOAL! ⚽</button>
<p id="score">Score: 0</p>
const goal = document.getElementById("goal");
const score = document.getElementById("score");
let goals = 0;

goal.addEventListener("click", () => {
  goals++;

  if (goals >= 10) {
    score.textContent = "Score: " + goals + " – hat trick and more! Player of the match 🏆";
  } else {
    score.textContent = "Score: " + goals;
  }
});
💡

本物のプログラミングを学んだ。 変数と条件は「ウェブだけ」じゃない——Python、ゲーム、アプリでも同じ。変数と条件が分かれば、どんなプログラミング言語とも話せる。

確認: カウンターが数え、上限に達したら追加の何かが起きる。コードを1行ずつ声に出して説明——できれば基礎は身についてる。

このレッスンのまとめ