Learn JavaScript in Construct, part 3: operators

35

Index

Features on these Courses

Stats

9,802 visits, 23,978 views

Tools

Translations

This tutorial hasn't been translated.

License

This tutorial is licensed under CC BY-NC 4.0. Please refer to the license text if you wish to reuse, share or remix the content contained within this tutorial.

Boolean operators

Remember previously we covered the boolean type, which are values that are either true or false. In this section we'll cover operators that either work on booleans, or produce a boolean result.

Comparisons

JavaScript provides several comparison operators which return a boolean. For example a < b returns true if a is less than b, otherwise it returns false. The comparison operators are:

  • Less than < and greater than >
  • Less than or equals <= and greater than or equals >=
  • Equals == and strict equals ===
  • Not equal != and strict not equal !==

Notice that since = is used for assignment, we have to use something else to test if numbers are actually equal. That's why two or three equals in a row are used, to distinguish comparison from assignment.

Why are there two kinds of equality? The standard equals == is allowed to convert types, and so can return true even if the types are different. The strict equals === does not convert types, so always returns false if the types are different.

// Try entering in to the console:
5 == 5		// true
5 == "5"	// true (converts types)
5 === 5		// true
5 === "5"	// false (types are different)

Similarly != can convert types and !== does not when testing for inequality.

// Try entering in to the console:
5 != "5"	// false (converts types)
5 !== "5"	// true (types are different)

It's generally regarded as best practice to prefer the strict equality comparisons === and !==. As noted previously automatic type conversion can lead to confusing results. For example if you are comparing a number to a string, it's often actually a mistake and you meant to convert something. Consistently using strict equals === and strict not equals !== avoids any confusion as they include comparing the type. For that reason, the rest of this guide will prefer using strict comparisons.

The less/greater operators don't have strict equivalents; unfortunately they can always convert values, such that "3" < 5 is true. We just have to live with this, but fortunately it's less often a problem than when testing equality.

It's also worth noting strings can be compared as less or greater. A string is considered less than another string if it would precede it in sort order. For example "apple" < "banana" is true because apple would come before banana in a sorted list (as this comparison is based on an alphabetical sort order).

  • 4 Comments

  • Order by
Want to leave a comment? Login or Register an account!