Lesson 6 · 6 of 20
Comparisons, logic and truthiness · JavaScript
The difference between === and == in JavaScript, the logical operators &&, || and !, and which values count as true or false (truthy and falsy).

`===` (strict equality) compares value and type: 5 === "5" is false because one is a number and the other text. `==` converts types before comparing, which is why 5 == "5" and even 0 == false give true. Always use === and its opposite !==: no surprises.
Logical operators combine conditions: && (and) needs both to be true, || (or) needs just one, and ! (not) flips the result. At 16 you cannot go to the concert alone, but age >= 18 || withAdult is true because an adult comes along.
In an if, any value counts as true or false. The falsy values are false, 0, "" (the empty string), null, undefined and NaN; everything else is truthy, even "0". That is why if (username) tells you whether the user typed anything.
|| returns the first truthy value it finds, so username || "Guest" gives a default when the name is empty. Boolean() shows how a value is read.
Code · main.js
// === compares value AND type; == converts types first (avoid it).console.log('5 === 5: ', 5 === 5);console.log('5 === "5": ', 5 === "5");console.log('5 == "5": ', 5 == "5");console.log("0 == false: ", 0 == false, "| 0 === false:", 0 === false);console.log('"apple" !== "Apple":', "apple" !== "Apple");// Logical operators: && (and), || (or), ! (not)const age = 16;const withAdult = true;console.log("Can enter the concert:", age >= 18 || withAdult);const isMember = true;const total = 80;console.log("Gets the discount:", isMember && total >= 50);console.log("Is not a member:", !isMember);// Truthy and falsy: in an if, every value counts as true or false.// Falsy: false, 0, "", null, undefined and NaN. Everything else is truthy.const username = "";if (username) { console.log(`Welcome, ${username}`);} else { console.log("Please type your name");}// || gives the first truthy value: handy for defaults.console.log("Name shown:", username || "Guest");console.log("Boolean(0):", Boolean(0), "| Boolean('0'):", Boolean("0"));Output · node main.js
5 === 5: true
5 === "5": false
5 == "5": true
0 == false: true | 0 === false: false
"apple" !== "Apple": true
Can enter the concert: true
Gets the discount: true
Is not a member: false
Please type your name
Name shown: Guest
Boolean(0): false | Boolean('0'): trueKey points
- Use
===and!==; avoid==. &&needs both conditions;||needs one;!negates.- Falsy:
false,0,"",null,undefined,NaN. value || fallbackgives a default value.
Exercise
Add a discount for anyone who is a member or spends over 100 euros, but never on Sundays (an isSunday variable), and try several combinations.