Operators

  1. Relational Operators

    basic: > < >= <= ==

    === (same as ==, but does not allow any type conversions)

    != (opposite of ==)

    !== (opposite of ===)

    == is to determine whether the values are equal.

    log(a<b<c) is incorrect. Because JS will count from left to right. a<b is true, but true<c is an incorrect expression and cannot be evaluated.


  2. Logical operators: && and, || or, !not

    b>a&&b<c The operation priority of && is higher than ||, even if it comes after the expression.

    ! has higher precedence than relational operators such as > and <. The way of writing !a>b is wrong, the correct way is !(a>b)


  3. Implicit type conversion

    JS automatically converts data types according to the differences between the two operations.

    1
    2
    3
    var a = 5;
    var b = "5";
    console.log(a==b) //true

    When boolean values and numbers are operated together, true is converted to 1 and false is converted to 0. (Boolean and string cannot be converted, because the automatic conversion itself is for numbers. If both parties involved in the operation are not numbers, there will be no automatic conversion.)


  4. Conversion of Boolean values

    In the case where Boolean values are required, only 6 data will be converted to false, and the others will be true.

    Convert to False: false, 0, " " (null character, not space), undefined, NaN (not a number), null


  5. && and ||

    If the element before && is false, the element before && will be returned directly; if the element before && is true, the result will be determined by the element after &&.

    1
    2
    console.log("hello"&&"world") //The result is world
    console.log(0&&"world") //The result is 0

    If the preceding || is false, the result is determined by the elements after ||; if the preceding || is true, the result directly returns the elements preceding ||.


  6. Assignment Operator

    = += -= *= /= %=

    var a=5; a+=5; Same as a++.


  7. Ternary operator ?:

    Syntax: Condition? Value when the condition is true: Value when the condition is not true

    1
    2
    3
    4
    var a=5;
    var b=6;
    var c=a>b?"haha":"hehe"
    console.log(c) //hehe

    Triple conditional judgment:

    1
    2
    3
    var a=5;
    var b=6;
    var c=a>b?"r1":(a<b?"r2":"r3")

  8. Summary

    When performing addition + (splicing) between strings and any type, the numbers are converted into strings;

    If you perform mathematical judgments and mathematical operations on numbers and any type, convert them to numbers.

    A simple way is to first consider what variable types should be on both sides of the operator (such as +, >, <, &&, etc.)? If both sides are not satisfied with the conditions, can they be converted into satisfied conditions? That is, + is addition or connection, < > is the size of a number, && is true/false.


Share