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 2.

This has mystified programmers and nonprogrammers alike. Most programmers agree that it is best to use strict comparison using the === operator. However, the rules for type coercion are very well defined in the language, and they are worth knowing about.

Let’s say you are trying to compare two variables: x == y. If they are the same type and have the same value, the comparison results in a Boolean true. The only exception to this is: If either x or y have the value NaN (the language constant meaning “not a number”), then the result is false.

However, if x and y are different types, things get a bit tricky. Here are some of the rules JavaScript applies:

  • These comparisons result in true: null == undefined and undefined == null.

  • When comparing a string and a number, first convert the string to its numerical equivalent. This means that "3" == 3 is true, and "dog" == 20 is false.

  • When comparing a Boolean to another type, first convert the Boolean to a number: true to the number 1, and false to the number 0. This means that false == 0 is true, and true == 1 is also true.

  • Finally, if you compare a string or a number to an object, first try to convert the object to a primitive value. If that conversion does not work, then try converting the object to a string.

For even more information, check out the MDN’s discussion at developer.mozilla.org/​en-US/​docs/​Web/​JavaScript/​Equality_comparisons_and_sameness.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.129.22.164