view core-javascript/equality.rst @ 201:b6864a86e876 default tip

Przetłumaczone getting-started
author Radomir Dopieralski <sheep-devel@sheep.art.pl>
date Sun, 15 Jul 2012 13:27:27 +0200
parents ff23e32bbe29
children
line wrap: on
line source

Equality
========

Equality in JavaScript can be a little odd.


Double equals
-------------

JavScript has two operations for equality (and inequality).  One of
them is '==' (and '!=' for inequality).  It's the oddest.


Not transitive
^^^^^^^^^^^^^^

If *a* is equal to *b*, and if *b* is equal to *c* , then we expect
*a* to be equal to *c*.  This is called the transitive property.


.. code-block:: javascript


   js> '0' == 0      // 'a' is equal to 'b'
   true
   js> 0 == ''      //  'b' is equal to 'c'
   true
   js> '0' == ''    // 'a' is not equal to 'c'
   false



Not reflexive
^^^^^^^^^^^^^

We expect *a* to be equal to *a*.  This is called the reflexive
property.

.. code-block:: javascript

   js> NaN == NaN
   false

Fortunately, this seems to be the only example.


Is symmetric
^^^^^^^^^^^^

If *a* is equal to *b* then we expect *b* to be equal to *a*.  This is
called the symmetric property.  In JavaScript equality is symmetric.



Triple equality
---------------

JavaScript also has '===' (and '!==' for inequality).


Is transitive
^^^^^^^^^^^^^

Unlike double equals, triple equals is always transitive.

.. code-block:: javascript

   js> '0' === 0      // unequal
   false
   js> 0 === ''       // unequal
   false
   js> '0' === ''     // unequal
   false


Not reflexive
^^^^^^^^^^^^^

.. code-block:: javascript

   js> NaN === NaN
   false


By the way, there's a thread on Facebook with subject `Time and Date
on my wall shows NaNNaNNaN at NaN:NaN
<http://www.facebook.com/topic.php?uid=4915599711&topic=54061>`_.  I
wonder how that happened.

Is symmetric
^^^^^^^^^^^^

Triple equality is still symmetric.


Don't use double equality
-------------------------

Double equality does implicit conversions and besides has some odd
rules.  My advice is **don't use double equality**.

Triple equality does not do conversions.  If you want to do
conversions in your comparision my advice is to make them explicit.


Compare as string
-----------------

The easiest conversion is to string.  Here are two immutables, a
number and a string.

.. code-block:: javascript

   js> a = 0
   0
   js> b = '0'
   0


These quantities are double equal but not triple equal.

.. code-block:: javascript

   js> a == b
   true
   js> a === b
   false

Here's how to do an explicit conversion to string before comparison,
which gives an equality.

.. code-block:: javascript

   js> '' + a === '' + b    // Converts variables to strings.
   true

.. note::

   It's always easier to read a triple equal comparison, because
   you're not distracted by the complex double equal rules.


Compare as number
-----------------

[To follow later.]