Common Mistakes
And how to avoid them.
Some JavaScript mistakes catch almost everyone. Let's look at a few, so you'll recognise them instantly when they happen to you.

- Mistakes everyone makes
- See them once
- Spot them forever
Four classic surprises
Adding a string and a number joins them, so ten plus five gives one oh five. Point one plus point two isn't exactly point three, because of how decimals are stored. Two arrays with the same items aren't equal, because they're different objects. And sort, with no function, sorts numbers as text. Run it.
console.log("10" + 5, Number("10") + 5);
console.log(0.1 + 0.2, (0.1 + 0.2).toFixed(2));
console.log([1, 2] === [1, 2]);
console.log([10, 9, 100].sort(), [10, 9, 100].sort((a, b) => a - b));105 15 0.30000000000000004 0.30 false [ 10, 100, 9 ] [ 9, 10, 100 ]
More to watch for
Forgetting await gives you a promise instead of a value. Using equals equals instead of three equals allows surprising conversions. Changing an array while looping over it skips items. And forgetting return in a function with curly braces gives undefined.
| key | value |
|---|---|
| Missing await | a Promise, not a value |
| == vs === | use === |
| Mutating in loops | skips items |
| Missing return | undefined |
Summary
Watch out for string joining, decimal rounding, comparing objects, sorting numbers, and missing awaits. Next, practice projects, starting with a word game.
Key takeaways- "10" + 5 is "105"
- 0.1 + 0.2
- sort((a, b) => a - b)