JavaScript's Weird Parts, Explained for Kids (and Confused Adults)

· 3 min read · Syed Omar Faruk Towaha
JavaScript's Weird Parts, Explained for Kids (and Confused Adults)

When I wrote a book teaching JavaScript to kids, the hardest part wasn't explaining loops or functions. Children get those quickly. The hardest part was the moment a curious kid typed something odd into the console and JavaScript answered with something even odder.

JavaScript being JavaScript
Every one of these has a sensible explanation. Mostly.

Let's explain the weirdness, so it stops being scary and starts being funny.

"5" + 2 is "52", but "5" - 2 is 3

The + sign has two jobs in JavaScript: adding numbers and joining strings. If either side is a string, it joins. So "5" + 2 becomes "52".

The - sign only has one job: subtracting numbers. So JavaScript converts "5" into the number 5 and gives you 3.

Lesson for kids: if you want a number, make it a number first.

const age = Number(prompt("How old are you?"));
console.log(age + 1);  // now this is real addition

0.1 + 0.2 is not 0.3

This isn't JavaScript's fault. Computers store numbers in binary, and 0.1 can't be written exactly in binary, just like 1/3 can't be written exactly in decimal (0.3333...). Python, Java and C do the same thing.

(0.1 + 0.2).toFixed(2);           // "0.30"
Math.abs(0.1 + 0.2 - 0.3) < 1e-9  // true: compare with a tiny tolerance

For money, count in cents (whole numbers) and divide at the end.

typeof NaN is "number"

NaN means "Not a Number," and it's the answer you get when maths goes wrong, like 0 / 0 or Number("banana"). It's a special number value that means "this calculation failed." So yes, Not-a-Number is a number. It's like a "Wrong Answer" sticker that's still technically an answer.

Even weirder: NaN === NaN is false. Use Number.isNaN(x) to check.

== vs ===

== tries to be helpful by converting types before comparing, which leads to things like 0 == "" being true. === compares without converting.

Rule: always use ===. Forget == exists. Your future self will thank you.

[] + [] is an empty string

Adding two arrays makes JavaScript convert them to strings first. An empty array becomes an empty string, and "" + "" is "". This is the kind of thing that's fun at parties for programmers, which are very specific parties.

So is JavaScript a bad first language?

Not at all. These quirks are real, but they're edges, not the middle. The middle of JavaScript is: you write a few lines, refresh the browser, and something on the screen changes. A button works. A game character moves. For a kid, that instant feedback is everything.

My advice for beginners of any age:

Every language has weird corners. JavaScript just happens to have its weird corners in the place where everyone can see them: the browser, in front of millions of curious people.

// related

// prefer the terminal?

Open the terminal blog and type read javascript-weird-parts-for-kids-and-adults.