JavaScript From Zero · 14 min · 100 XP
Coercion, equality and truthiness
Know when JavaScript changes a value's type behind your back, and compare and test values safely.
Every value from the last lesson has a type. JavaScript will also change a value's type for you, without asking, and that's where most beginner bugs live.
+ joins, - subtracts
"5" + 1 is "51": when either side of + is a string, + joins text. But "5" - 1 is 4, because - only does maths, so it converts the string first. Form fields always give you strings, so convert on purpose with Number(text), and watch out: Number("") is 0, not "nothing". .trim() removes spaces from both ends of a string, so " 3.5 ".trim() is "3.5"; the strings lesson covers more.
"5" + 1 // "51" joined
"5" - 1 // 4 converted, then subtracted
Number("5") + 1 // 6 converted on purpose
Number("") // 0 an empty field is not "nothing"
" 3.5 ".trim() // "3.5"Compare with ===
== converts before comparing, so 0 == "", "1" == 1 and null == undefined are all true. === compares the type as well as the value, and converts nothing. Always use ===; then a comparison means exactly what it says.
Truthy and falsy
In an if, these count as false: false, 0, "", null, undefined and NaN. Everything else is true, including "0", [] and {}. So if (quantity) treats a genuine quantity of 0 as missing. When 0 or an empty string is a real answer, test for what you mean, such as quantity === null; the conditionals lesson shows ?? for defaults.
Loading your workspace…