If/Else & Truthy/Falsy

Duration: 10 min•Difficulty: Medium•

Branch logic (IF) in JavaScript is very commonly used.

If / Else

main.js
const score = 85;
if (score >= 90) {
console.log("Grade A");
} else if (score >= 80) {
console.log("Grade B");
} else {
console.log("Grade C");
}

Truthy & Falsy Values

In addition to pure true/false values, JS considers all values as "Truthy" (considered true when put into an IF check), EXCEPT THESE 6 ELEMENTS:

  1. false
  2. 0
  3. "" (Empty string)
  4. null
  5. undefined
  6. NaN (Not a Number)
main.js
let userName = ""; // Empty string
if (userName) {
console.log("Hello " + userName);
} else {
// Forced into ELSE because an empty string is considered 'Falsy'.
console.log("Please enter your name!");
}