Skip to content

Instantly share code, notes, and snippets.

@leakypixel
Last active August 29, 2015 14:02
Show Gist options
  • Save leakypixel/ddc0dbf8a0fc6902053c to your computer and use it in GitHub Desktop.
Save leakypixel/ddc0dbf8a0fc6902053c to your computer and use it in GitHub Desktop.
JavaScript comparison notes

###JavaScript has both strict and type-converting comparison.

For strict equality the objects being compared must have the same type, and:

  • Two strings are strictly equal when they have the same sequence of characters, same length, and same characters in corresponding positions.
  • Two numbers are strictly equal when they are numerically equal (have the same number value).
  • NaN is not equal to anything, including NaN.
  • Positive and negative zeros are equal.
  • Boolean operands are strictly equal if both are true or both are false.
  • Objects are strictly equal only if they refer to the same Object instance.
  • Null and Undefined are ==, but not === (they're not of the same type, because they have no real type - they're absence).

For type-converting equality:

  • Whitespace, empty strings and zeroes are considered falsey.
  • Undefined and null are both non-values (neither true nor false).
  • A string with any value other than whitespace, zero, or empty is considered truey.
  • After these type-conversions have been made, follow the same rules as strict.

Examples:

  1. '' == '0' // false, they're both treated as strings (note the quotes!) - this isn't a cross-type comparison.
  2. 0 == '' // true, the string has a zero/falsey value (whitespace), and zero is falsey.
  3. 0 == '0' // true, the zero here is considered falsey, same as whitespace.
  4. false == 'false' // false, the string has a non-zero/non-falsey value.
  5. false == '0' // true, for the same reason as 3.
  6. false == undefined // false, undefined is absence, nothing, a non-value.
  7. false == null // false, for the same reason as 6.
  8. null == undefined // true, they're both non-values.
  9. ' \t\r\n ' == 0 // true, again whitespace is considered falsey.

Sources: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators http://stackoverflow.com/questions/359494/does-it-matter-which-equals-operator-vs-i-use-in-javascript-comparisons http://stackoverflow.com/questions/523643/difference-between-and-in-javascript

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment