計算し、===で値を比較し、ifとelseでプログラムに判断させる方法を学びましょう。
このレッスンを Kodokon で開く演算子とは、値に対して演算を行う記号です。算術演算子は学校で習ったのですでに知っているでしょう。+(加算)、-(減算)、*(乗算)、/(除算)です。JavaScriptには剰余である%が加わり、これは整数の割り算の余りを返します。たとえば、数が偶数かどうかを調べるのに便利です。
const a = 10;
const b = 3;
console.log(a + b); // Prints: 13
console.log(a - b); // Prints: 7
console.log(a * b); // Prints: 30
console.log(a % b); // Prints: 1 (the remainder)判断を下すために、プログラムは値を比較する必要があります。比較とは、答えが真偽値(trueまたはfalse)になる問いです。比較演算子は>(より大きい)、<(より小さい)、>=(以上)、<=(以下)、===(厳密に等しい)、!==(厳密に等しくない)です。===演算子は、二つの値が同一でかつ同じ型であることを確認します。
console.log(5 > 3); // true
console.log(5 < 3); // false
console.log(5 >= 5); // true
console.log(5 === 5); // true
console.log(5 === "5"); // false: different types
console.log(5 !== 3); // trueいよいよ判断です! if文は、条件が真のときだけコードのブロックを実行します。elseブロックは、条件が偽のときに実行されます。条件は丸括弧の中に、各ブロックは波括弧{ }の中に書きます。
const age = 17;
if (age >= 18) {
console.log("You are an adult.");
} else {
console.log("You are a minor.");
}
// Prints: You are a minor.5 === "5"の値は何ですか?if / else構造で、elseブロックはいつ実行されますか?