You get a bonus - 1 coin for daily activity. Now you have 1 coin

Comparison Operators and Boolean Values

Lecture




  1. Boolean values
  2. String comparison
  3. Comparison of different types
  4. Strict equality
  5. Comparison with null and undefined
  6. Total

In this section, we will introduce the comparison operators and the logical values ​​that such operators return.

Many comparison operators are familiar to us from school:

  • Over / Under: a > b , a < b .
  • Greater than / less than or equal to: a >= b , a <= b .
  • Equal to a == b .
    For comparison, two equal symbols '=' . One character a = b would mean assignment.
  • "Not equal". At school, it is written as , in JavaScript - an equal sign with an exclamation mark in front of it != .

Boolean values

Like other operators, the comparison returns a value. This value has a special logical type.

There are only two logical values:

  • true - it makes sense "yes", "true", "truth".
  • false - means “no”, “false”, “false”.

For example:

1 alert( 2 > 1 ); // true, верно
2 alert( 2 == 1 ); // false, неверно
3 alert( 2 != 1 ); // true

Logical values ​​can be used directly, assign variables, work with them as with any other:

1 var a = true ; // присвоили явно
2 var b = 3 > 4; // false
3
4 alert( b ); // false
5
6 alert( a == b ); // (true == false) неверно, результат false

String comparison

Strings are compared letter by letter:

1 alert( 'Б' > 'А' ); // true

Letters are compared alphabetically. What letter in the alphabet later is the one and more.

Unicode encoding

An analogue of the “alphabet” in the internal representation of strings is the encoding, each character has its own number (code). JavaScript uses Unicode encoding. This compares the numeric character codes .

In Unicode, the lowercase letter is usually larger than the lowercase letter, so:

1 alert( 'а' > 'Я' ); // true, строчные буквы больше прописных

For correct comparison, the characters must be in the same register.

The comparison is carried out as in the phone book or in the dictionary. First, the first letters are compared, then the second, and so on, until one is more than the other.

In other words, more is the line that in the phone book would be on a larger page.

For example:

  • If the first letter of one line is larger, then the first line is greater, regardless of the other characters:

    1 alert( 'Банан' > 'Аят' );

  • If the same - the comparison goes on. Here it will reach the third letter:

    1 alert( 'Вася' > 'Ваня' ); // true, т.к. 'с' > 'н'

  • However, any letter is greater than the absence of a letter:
    1 alert( 'Привет' > 'Прив' ); // true, так как 'е' больше чем "ничего".

Such a comparison is called lexicographic .

Usually we get the values ​​from the visitor as strings. For example, prompt returns the string that the visitor entered.

The numbers obtained in this way cannot be compared in the form of strings, the result will be incorrect. For example:

1 alert( "2" > "14" ); // true, неверно, ведь 2 не больше 14

In the example above, 2 turned out to be more than 14 , because the strings are compared character by character, and the first character '2' greater than '1' .

It would be correct to convert them to the number explicitly. For example, putting in front of them + :

1 alert( + "2" > + "14" ); // false, теперь правильно

Comparison of different types

When comparing values ​​are converted to numbers. Exception: when both values ​​are strings, then they are not converted.

For example:

1 alert( '2' > 1 ); // true
2 alert( '01' == 1 ); //true
3 alert( false == 0 ); // true, false становится 0, а true 1.

The topic of type conversions will be continued further in the chapter Object Conversions: toString and valueOf.

Strict equality

Normal equality cannot distinguish 0 from false :

1 alert(0 == false ); // true, т.к. false преобразуется к 0

What to do if you still need to distinguish 0 from false ?

To test equality without type conversion, the strict equality operators are used === (triple equals) and !== .

They compare without type conversion. If the type is different, then such values ​​are always unequal (strictly):

1 alert(0 === false ); // false, т.к. типы различны

Comparison with null and undefined

Problems with special values ​​are possible when the comparison operation is applied to the variable > < <= >= , and it can have both a numerical value and null/undefined .

Intuitively, it seems that null/undefined equivalent to zero, but this is not so! They behave differently.

  1. The values null and undefined are equal == each other and are not equal to anything else.
    This hard rule is literally spelled out in the language specification.
  2. When converted to a number, null becomes 0 , and undefined becomes NaN .

Let's see funny consequences.

Invalid null - 0 comparison result

Compare null with zero:

1 alert( null > 0); // false
2 alert( null == 0); // false

So, we got that null no more and is not zero. And now…

1 alert( null >= 0); // true

How is this possible? If something is “greater than or equal to zero,” then it is reasonable to believe that it is either more or equal . But here it is not.

The fact is that equality == and comparison >= > < <= algorithms work differently.

Comparison honestly leads to a number, it turns out zero. And when checking equality, null and undefined values ​​are processed in a special way: they are equal to each other, but not equal to something else.

The result is a strange from the point of view of common sense situation, which we saw in the example above.

Incomparable undefined

The value undefined cannot be compared at all:

1 alert( undefined > 0); // false (1)
2 alert( undefined < 0); // false (2)
3 alert( undefined == 0); // false (3)

  • Comparisons (1) and (2) give false because undefined when converted to a number, gives NaN . And the NaN value according to the standard is arranged so that comparisons == , < , > , <= , >= and even === with it return false .
  • Checking equality (3) gives false , because the standard explicitly states that undefined is only null and nothing else.

Conclusion: any comparison with undefined/null , except for exact === , should be done with caution. It is advisable not to use comparisons >= > < <= , in order to avoid errors in the code.

Total

  • JavaScript has logical values true (true) and false (false). Comparison operators return them.
  • Strings are compared letter by letter.
  • Values ​​of different types are reduced to a number when comparing, with the exception of strict equality === ( !== ).
  • The values null and undefined are equal == each other and are not equal to anything else. In other comparisons (with the participation of > , < ), it is better not to use them, since they do not behave as 0 .
created: 2014-10-07
updated: 2021-03-13
132541



Rating 9 of 10. count vote: 2
Are you satisfied?:



Comments


To leave a comment
If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Scripting client side JavaScript, jqvery, BackBone

Terms: Scripting client side JavaScript, jqvery, BackBone