Key operators

Lecture




  1. Terms: “unary”, “binary”, “operand”
  2. Arithmetic operators
    1. Addition of lines, binary +
    2. Unary plus +
  3. Assignment
  4. A priority
  5. Increment / Decrement: ++, --
  6. Bitwise operators
  7. Calling Assigned Operators
  8. Operator comma

To work with variables, with values, JavaScript supports all standard operators, most of which are in other programming languages.

Terms: “unary”, “binary”, “operand”

Operators have their own terminology, which is used in all programming languages.

  • The operand is what the operator applies to. For example: 5 * 2 - multiplication operator with left and right operands. Another name: operator argument.
  • Unary is an operator that is applied to a single expression. For example, the operator unary minus "-" changes the sign of a number to the opposite:

    1 var x = 1;
    2 alert( -x ); // -1, унарный минус
    3 alert( -(x+2) ); // -3, унарный минус применён к результату сложения x+2
    4 alert( -(-3) ); // 3

  • Binary is the operator that is applied to two operands. The same minus exists in binary form:

    1 var x = 1, y = 3;
    2 alert( y - x ); // 2, бинарный минус

The operation of the unary "+" and binary "+" in JavaScript is significantly different.

These are really different operators. Binary plus adds operands, and unary - does nothing in arithmetic terms, but it leads the operand to a numeric type. Next we will see examples.

Arithmetic operators

The basic arithmetic operators have been familiar to us since childhood: this is plus + , minus - , multiply * , divide / .

For example:

1 alert(2 + 2); // 4

Or a bit more complicated:

1 var i = 2;
2
3 i = (2 + i) * 3 / i;
4
5 alert(i); // 6

The rarer arithmetic operator % interesting because it has nothing to do with interest. Its result, a % b , is the remainder of dividing a by b .

For example:

1 alert(5 % 2); // 1, остаток от деления 5 на 2
2 alert(8 % 3); // 2, остаток от деления 8 на 3
3 alert(6 % 3); // 0, остаток от деления 6 на 3

Addition of lines, binary +

If the binary operator + applied to strings, then it combines them into one:

var a = "моя" + "строка" ;
alert(a); // моястрока

If at least one argument is a string, the second one will also be converted to a string!

And it does not matter whether the operand string is on the right or left, in any case the non-string argument will be converted. For example:

1 alert( '1' + 2 ); // "12"
2 alert( 2 + '1' ); // "21"

This cast to a string is a feature of the binary operator "+" .

The remaining arithmetic operators work only with numbers and always bring the arguments to a number.

For example:

1 alert( '1' - 2 ); // -1
2 alert( 6 / '2' ); // 3

Unary plus +

Unary plus as an arithmetic operator does nothing:

1 alert( +1 ); // 1
2 alert( +(1-2) ); // -1

As you can see, plus did not change anything in expressions. The result is the same as without it.

Nevertheless, it is widely used, since its “side effect” is the conversion of a value into a number.

For example, we have two numbers, in the form of strings, and we need to add them. Binary plus adds them up as strings, so we use unary plus to convert to a number:

1 var a = "2" ;
2 var b = "3" ;
3
4 alert( a + b ); // "23", так как бинарный плюс складывает строки
5 alert( +a + b ); // "23", второй операнд - всё ещё строка
6
7 alert( +a + +b); // 5, число, так как оба операнда предварительно преобразованы в числа

Assignment

The assignment operator looks like the equals sign = :

var i = 1 + 2;
alert(i); // 3

It evaluates the expression that is on the right, and assigns the result to a variable. This expression can be quite complex and include any other variables:

1 var a = 1;
2 var b = 2;
3
4 a = b + a + 3; // (*)
5
6 alert(a); // 6

In line (*) , a calculation will first be performed using the current value of a (i.e. 1 ), after which the result will overwrite the old value of a .

Possible assignment on the chain:

1 var a, b, c;
2
3 a = b = c = 2 + 2;
4
5 alert(a); // 4
6 alert(b); // 4
7 alert(c); // 4

Such an assignment works from right to left, that is, the rightmost 2+2 expression is calculated first, assigned to c , then b = c and, finally, a = b .

Operator "=" returns value

All operators return value. A call to x = выражение writes the expression to x , and then returns it. Because of this, the assignment can be used as part of a more complex expression:

1 var a = 1;
2 var b = 2;
3
4 var c = 3 - (a = b + 1);
5
6 alert(a); // 3
7 alert(c); // 0

In the example above, the result (a = b + 1) is a value that is written to a (i.e. 3 ). It is used to calculate c .

A fun use of assignment, right?

To know how it works is necessary, but to write oneself only if you are sure that it will make the code more readable and understandable.

A priority

If there are several operators in the expression, the order of their execution is determined by the priority .

From school we know that the multiplication in the expression 2 * 2 + 1 will be executed before addition, since its priority is higher, and parentheses explicitly specify the order of execution. But in JavaScript, there are much more operators, so there is a whole table of priorities.

It contains both already passed operators, and those that we have not yet passed. In it, each operator is given a numerical priority. Anyone who has a lower number will be executed earlier. If the priority is the same, the execution order is from left to right.

Excerpt from the table:

... ... ...
five multiplication *
five division /
6 addition +
6 subtraction -
17 assignment =
... ... ...

Let's look at the table in action.

In the expression x = 2 * 2 + 1 there are three operators: assignment = , multiplication * and addition + . The multiplication priority * is 5 , it will be executed first, then there will be an addition + , whose priority is 6 , and after them - assignment = , with priority 17.

Increment / Decrement: ++, --

One of the most frequent operations in JavaScript, as in many other programming languages, is to increment or decrement a variable by one.

There are even special operators for this:

  • Increment ++ increases by 1:
    1 var i = 2;
    2 i++; // более короткая запись для i = i + 1.
    3 alert(i); // 3
  • Decrement -- reduces by 1:
    1 var i = 2;
    2 i--; // более короткая запись для i = i - 1.
    3 alert(i); // 1

Increment / Decrement can only be applied to a variable.
Code 5++ will give an error.

You can call these operators not only after, but also before a variable: i++ (called “postfix form”) or ++i (“prefix form”).

Both of these forms of recording do the same thing: increase by 1 .

However, there is a difference between them. It is visible only in the case when we want not only to increase / decrease the variable, but also to use the result in the same expression.

For example:

1 var i = 1;
2 var a = ++i; // (*)
3
4 alert(a); // 2

In line (*) call to ++i will increment the variable, and then return its value to a . That is, a gets the value of i after increasing .

The postfix form i++ differs from the prefix ++i in that it returns the old value that was before the increase.

In the example below, a gets the old value of i , equal to 1 :

1 var i = 1;
2 var a = i++; // (*)
3
4 alert(a); // 1

  • If the result of the operator is not used, it is only necessary to increase / decrease the variable - no matter what form to use:
    1 var i = 0;
    2 i++;
    3 ++i;
    4 alert(i); // 2
  • If you want to immediately use the result, then you need a prefix form:
    1 var i = 0;
    2 alert( ++i ); // 1
  • If you need to increase, but you need the value of the variable before increasing - the postfix form:
    1 var i = 0;
    2 alert( i++ ); // 0

Increment / Decrement can be used in any expression.

At the same time, it has a higher priority and is executed earlier than arithmetic operations:

1 var i = 1;
2 alert( 2 * ++i ); // 4

1 var i = 1;
2 alert( 2 * i++ ); // 2, выполнился раньше но значение вернул старое

At the same time, it is necessary to use such a record with caution, because when reading a code it is often not obvious that changing increases. Three lines are longer, but clearer:

1 var i = 1;
2 alert( 2 * i );
3 i++;

Importance: 5

Look, do you understand why the code below works that way?

01 var a = 1, b = 1, c, d;
02
03 c = ++a; alert(c); // 2
04 d = b++; alert(d); // 1
05
06 c = (2+ ++a); alert(c); // 5
07 d = (2+ b++); alert(d); // 4
08
09 alert(a); // 3
10 alert(b); // 3

Decision

01 var a = 1, b = 1, c, d;
02
03 // префиксная форма сначала увеличивает a до 2, а потом возвращает
04 c = ++a; alert(c); // 2
05
06 // постфиксная форма увеличивает, но возвращает старое значение
07 d = b++; alert(d); // 1
08
09 // сначала увеличили a до 3, потом использовали в арифметике
10 c = (2+ ++a); alert(c); // 5
11
12 // увеличили b до 3, но в этом выражении оставили старое значение
13 d = (2+ b++); alert(d); // 4
14
15 // каждую переменную увеличили по 2 раза
16 alert(a); // 3
17 alert(b); // 3

[Open task in new window]

Bitwise operators

Bitwise operators treat arguments as 32-bit integers and operate at the level of their internal binary representation.

These operators are not JavaScript-specific, they are supported in most programming languages.

The following bitwise operators are supported:

  • AND (i) ( & )
  • OR (or) ( | )
  • XOR (bitwise exclusive or) ( ^ )
  • NOT (not) ( ~ )
  • LEFT SHIFT (left shift) ( << )
  • RIGHT SHIFT (right shift) ( >> )
  • ZERO-FILL RIGHT SHIFT (right shift with padding with zeros) ( >>> )

You can read more about them in a separate article, Bitwise Operators.

Calling Assigned Operators

Often you need to apply an operator to a variable and save the result in it, for example:

var n = 2;
n = n + 5;
n = n * 2;

This record can be shortened using combined operators: +=, -=, *=, /=, >>=, <<=, >>>=, &=, |=, ^= .

Like this:

1 var n = 2;
2 n += 5; // теперь n=7 (работает как n = n + 5)
3 n *= 2; // теперь n=14 (работает как n = n * 2)
4
5 alert(n); // 14

All of these operators have exactly the same priority as regular assignment, that is, they are executed after most other operations.

Importance: 3

What will be x in the example below?

var a = 2;
var x = 1 + (a *= 2);

Decision

Answer: x = 5 .

The assignment operator returns the value that will be written to the variable, for example:

1 var a = 2;
2 alert( a *= 2 ); // 4

Hence x = 1 + 4 = 5 .

[Open task in new window]

Operator comma

Comma is also an operator. It can be called explicitly, for example:

1 a = (5, 6);
2
3 alert(a);

A comma allows you to list expressions, separating them with a comma ',' . Each of them is calculated and discarded, with the exception of the last, which is returned.

A comma is the only operator whose priority is lower than assignment. In the expression a = (5,6) , the parentheses are used to explicitly set the priority, otherwise the operator '=' would execute to the comma ',' , it would turn out (a=5), 6 .

Why do we need such a strange operator, which discards the values ​​of all the listed expressions, except the last one?

Usually it is used in the composition of more complex structures to do several actions in one line. For example:

1 // три операции в одной строке
2 for ( a = 1, b = 3, c = a*b ; a < 10; a++) {
3   ...
4 }

Such tricks are used in many JavaScript frameworks to shorten code.


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