For the More Curious: Rules for Type Coercion

As mentioned in Chapter 6, JavaScript was originally created so that folks who were not professional programmers could add interactivity to web pages. It was thought that these “regular humans” should not need to worry about whether a value was a number, an object, or a banana. (Just kidding – there is no banana type in JavaScript.)

One of the ways this is achieved is through type coercion. With type coercion, you can compare two values, regardless of their types, using the == operator and concatenate two values using the + operator. When you do, JavaScript will figure out a way to make that work – even if it has to do something a little weird, like changing the string "2" to the number ...

Get Front-End Web Development: The Big Nerd Ranch Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.