javaScript family [17] - operators

This article will introduce the operators in javaScript language, including but not limited to arithmetic operators, logical operators, relational operators and assignment operators, while it will only briefly describe bit operators and keyword operators.

Introduction to operators

If the operators in JavaScript language are divided according to symbols, they can be divided into two categories: operators represented by punctuation and keyword operators. The former refers to operators similar to +, *, & &, = = and the latter refers to operators similar to in, delete, typeof and instanceof. It should be noted that this paper only introduces the former, that is, the operator represented by punctuation.

In fact, if operators are divided according to their functions and specific use methods, they can be divided into basic arithmetic operators, logical operators, relational operators, assignment operators, etc. as shown in the above figure, which is also the customary classification method in development. It sounds very complicated and even frightening. In fact enmmm~ it's not necessary ** : )**

Operator basic usage

Next, I will introduce various types of operators in JavaScript, including what specific operators they have, how they should be used, the sample code used, and additional points for attention (bitwise operators are not within the scope of this article, and interested friends can refer to them) Data security series XOR This article.

Basic arithmetic operator

Here we first introduce the basic arithmetic operators, which are *(multiplication), / (Division), + (addition), - (subtraction) and% (modulo operation) . Among these operators, except that + (addition) is slightly more complex, the other four operators are very simple, that is, simple quadrature, quotient, difference and remainder.

  var num1 = 8,num2 = 26;

  /*Basic arithmetic operators*/
  console.log(num1 + num2);     //34
  console.log(num2 - num1);     //18
  console.log(num1 - num2);     //-18
  console.log(num1 * num2);     //208
  console.log(num1 / num2);     //0.3076923076923077
  console.log(num2 / num1);     //3.25
  console.log(num2 % num1);     //2
  console.log(num1 % num2);     //8

Notes on the use of arithmetic operators

① In addition to addition, other operators convert operands to numbers when necessary. If they cannot be converted, the result is NaN.
② The result of divisor 0 is positive infinity or negative infinity, and the result of 0 / 0 is NaN.
③ In the modulo (%) operation, the result of the calculation is consistent with the sign of the first operand, and the modulo operation is also applicable to integers and floating-point numbers.
④ Addition (+) can be used to add two numbers or connect strings. For details, please refer to the following example code.

  /*Note on the use of arithmetic operators*/
  /*01 By default, non numbers are converted to numbers. If they cannot be converted, they are converted to NaN, and the final result is NaN*/
  console.log("12" - 3);            //9
  console.log("12" / 3);            //4
  console.log("12a"* 3);            //NaN

  /*02 Consider the case of 0 as divisor*/
  console.log("12" / 0);            //Infinity infinity
  console.log(-12  / 0);            //-Infinity negative infinity
  console.log( 0   / 0);            //NaN

  /*03 The symbolic problem of modular operation and its application in floating point numbers*/
  console.log("12"  % 1  );         //0
  console.log("-12" % 5  );         //-2
  console.log("-12" % -5 );         //-The sign of the result of the 2-modulo operation is only related to the first operand
  console.log( 6.5  % 2.1);         //0.19999999999999973

  /*04 Addition is used to splice the usage and precautions of strings*/
  console.log(1 + 2);               //3
  console.log("Hi" + " XiaoXia");   //"Hi XiaoXia"
  console.log("2"  + "3");          //"23"
  console.log("2"  +  3 );          //"23"
  console.log( 2   + "3");          //"23"
  console.log( 1   + 2 + "Nice" );  //"3Nice"
  console.log( 1   + (2 + "Nice")); //"12Nice"
  console.log("Nice" + 1 + 2);      //"Nice12"

  console.log(true + true);         //2 Boolean values are converted to the number 1 before addition
  console.log(true + false);        //1
  console.log(41   + null);         //41 null is converted to the number 0 before adding
  console.log(41   + undefined);    //NaN undefined is converted to a number (NaN) and added

In particular, when dealing with the + operator, if the operands are all numbers, add them. If they are all strings, splice them. In other cases, the operation will perform the necessary type conversion by default, and the behavior of the operator depends on the result of type conversion. The conversion rules of the plus sign need to give priority to string connection.

Relational operator

Relational operators are used to test the relationship between two values, such as "equal" and "greater than". They return true or false according to whether the relationship exists (holds). Relational expressions always return a Boolean value It is usually used in if, while and for statements to control the execution flow of the program. The comparison operators (<, < =, >, > =) and (not) phase (all) operators in relational operators will be introduced in turn.

The comparison operator is used to detect the size relationship between two operands( Value size or alphabetical order ). It should be noted that JavaScript strings are a sequence of 16 bit integer values. String comparison is essentially to compare the values corresponding to the characters in two strings, and string comparison is case sensitive. All uppercase ASCII letters are "less than" lowercase ASCII letters, Click to view ASCII table.

  /*Simple use of comparison operators: return values are Boolean values*/
  /*01-When both operators are numbers*/
  console.log(1  <  3 );        //true
  console.log(12 <  4 );        //false
  console.log(1  <= 3 );        //true
  console.log(65 >  41);        //true
  console.log(65 >= 41);        //true

  /*02-When both operators are strings*/
  console.log("a"  <  "b"  );   //true  "a"-97 "b"-98
  console.log("a"  <  "ba" );   //true compare first
  console.log("ab" >  "ac" );   //false compare second bit b-98 c-99
  console.log("abc"<  "abx");   //true compares the third digit c-99 x-120
  console.log("1"  >  "2" );    //false "1"-49 "2"-50
  console.log("A"  >  "a" );    //false "A"-65 "a"-97

The operands of comparison operators can be of any type, but only numbers and strings can really perform comparison operations. Other operations will be type converted. In type conversion, the comparison operator prefers numbers, so it will first convert the operands to numbers for comparison. String comparison (alphabetic order) will be carried out only when both operands are strings.

  /*If the two operand types of the comparison operator are not both string and number~*/
  console.log("a"  >  0 );       //False "a" is converted to NaN
  console.log(100  > "c");       //False "C" converted to NaN
  console.log("12" >  10);       //True "12" is converted to the number 12
  console.log(10   > undefined); //False undefined to NaN
  console.log(10   > null);      //True null to 0
  console.log(-1   > null);      //false   

In a brief summary, if the two operands of the comparison operator have different types (not all numbers or not all strings), the operands will be converted to numbers first. If NaN appears in the operand (either before or after type conversion), the final result will be NaN.

The equal () and congruent (=) operators are used to compare whether two values are equal or congruent. If they are satisfied, they return true. actually The core difference between equality () and congruence (=) is that equality only compares values, while congruence needs to compare values and types.

  /*Equal: only compare values. If the types are different, type conversion (limited to string, Boolean value and object) will be carried out, and the conversion to number is preferred*/
  console.log( 1   == 1);         //true
  console.log("1"  == 1);         //True '1' is first converted to the number 1
  console.log("1a" == 1);         //False "1A" is first converted to a number, where NaN is obtained
  console.log(true == 1);         //True true is first converted to the number 1
  console.log(true == "1");       //True true is first converted to the number 1, and "1" is converted to the number 1

  console.log(NaN  == NaN);       //False Nan is not equal to any value, including itself
  console.log(null == undefined); //true is special (because undefined essentially derives from null)

  /*Note: undefined and null are not converted to NaN and 0 when compared with numbers*/
  console.log(0    == undefined); //false
  console.log(0    == null);      //false

  /*Congruence: also known as strict equality, it compares both values and types. If the types are different, false will be returned directly*/
  console.log("1"  === 1);         //false type is different
  console.log(true === 1);         //false type is different
  console.log(null === undefined); //false type is different

Note: it is necessary to distinguish "= =" (equal), "= = =" (congruent) and "=" (assignment). In addition, there are "! =" and "! = =" operators, whose detection rules are just the negation of equality and congruence.

Logical operator

The diagram has listed three logical operators in JavaScript language ("logical not", "logical or" and "logical and") and their specific usage. In development, logical operators are often used in conditional expressions (such as conditional judgment of if statements). The reference code is given below.

  /*01-Logical non this operator has only one operand, which is used to negate the operand*/
  console.log(!true);             //false
  console.log(!0);                //true
  console.log(!undefined);        //true

  /*02-Logical or this operator requires two operands
  * Operation rule: if the first operand is true, the first operand will be returned directly; otherwise, the second operand will be returned
  */
  console.log(   0 || 1);        //1
  console.log(true || false);    //true returns the operand 1
  console.log(   1 || 2);        //1 returns the operand 1
  console.log(   2 || 4);        //2 return operand 1
  console.log(  "" || 5);        //5 the first operand is converted to false and the second operand is returned
  console.log( 1>2 || "Hi");     //Hi"

  /*03-Logical and this operator requires two operands
  * Operation rule: if the first operand is true, the second operand will be returned directly; otherwise, the first operand will be returned
  */
  console.log(   0 && 1);        //0
  console.log(true && false);    //false returns the operand 2
  console.log(   1 && 2);        //2 return operand 2
  console.log(   2 && 4);        //4 return operand 2
  console.log(  "" && 5);        //""
  console.log( 1>2 && "Hi");     //false

Other common operators

At last, we briefly introduce the assignment operator, self increasing and self decreasing operator and special ternary operator in JavaScript language.

Assignment operator JavaScript uses the = operator to assign a value to a variable. The operator wants its left operand to be an lvalue (a variable or object attribute), and its right operand can be any value of any type. It should be noted that the priority of = is very low, and its associativity is from right to left (that is, if there are multiple assignment operators in an expression, the operation order is from right to left).

var a = 8.26;             //Set the value of variable a to 8.26
    a = "Xia";            //Quadratic assignment
    
var i,j=k=o=408;          //Initialize the variables j, k and o to 408
console.log(i, j, k,o);   //undefined 408 408 408

Assignment operators with operations mainly include + =, - =, * =, / = and% =. Of course, it also includes the combination of < < = equipotential operator and assignment operator (this article does not involve bitwise operator). These operators listed here are actually a combination of arithmetic operators and assignment operators. They are a common abbreviation. The example code is given below.

  var a = 1,b = 2;
  console.log(a += b);  //Equivalent to a = a + B 3 (this is the updated value of a)
  console.log(a -= b);  //Equivalent to a = a - B 1
  console.log(a *= b);  //Equivalent to a = a * B 2
  console.log(a /= b);  //Equivalent to a = A / B 1
  console.log(a %= b);  //Equivalent to a = a% B 1

Now, let's look at the self increasing (+ + i or i + +) and self decreasing (- - i or i --) operators often used in development. Their function is to + 1 or - 1 based on the current value, while + + i and i + + have no difference for the variable i itself. The difference is that if there is an operation involving returning the value, Then the update of + + i will be reflected in the return value (in other words, first return the + 1 of the variable and then return the result), while i + + will not (first return i and then perform the + 1 operation of the variable). The same is true for the self subtraction operator.

  /*Note: i + + is equivalent to i = i + 1*/
  var i  = 0;
  var r1 = i++;     //First assign the value of i to r1, and then execute i+1
  console.log(i);   //1
  console.log(r1);  //0

  var j  = 0;
  var r2 = ++j;     //First execute j+1, and then assign the value of j+1 to r2
  console.log(j)    //1
  console.log(r2);  //1

  /*Thinking: var k = 0; console.log(k++ + ++k + k  + k++);*/

The conditional operator (?:) is also called a ternary operator because it requires three operands. The syntax is * * conditional expression? Expression 1: expression 2 * *, whose operation rule is to check the value of conditional expression. If the value is true, expression 1 is returned; otherwise, expression 2 is returned.

var a = 1 < 2 ? "less than" : "greater than";              //The result of conditional expression 1 < 2 is true
console.log(a);     //less than

var b = (1 < 2) && (3 > 5) ? "read a book" : "sleep";//The result of the conditional expression is true (false)
console.log(b);    //sleep

Operator priority remarks when writing JavaScript expressions, we should pay attention to that operators have priority, such as var a = x + y * b; This line of code, because the multiplication operator takes precedence over the addition operator, followed by the equal sign assignment operator, its execution order is to calculate the value of y * b, then + X, and finally assign the result to a. In development, we can forcibly specify the operation order through parentheses. If var a = (x + y) * b; If you write the code like this, add and multiply first, and then assign the value.

Added by moniphp on Tue, 04 Jan 2022 01:43:34 +0200