AI Hints
Home›JavaScript Tutorial›Debugging and Clean Code
JavaScript · Lesson 114 of 138

Common Mistakes

And how to avoid them.

⏱ 2 min read▶ Video at 2:17:16🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

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

Common Mistakes
From the video: Common Mistakes
  • 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.

app.jsjavascript
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));
Output
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.

keyvalue
Missing awaita Promise, not a value
== vs ===use ===
Mutating in loopsskips items
Missing returnundefined

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)
Next up: Practice: Word Guess — a small game