JAVASCRIPT OPERATORS

JSBefore we begin, let us understand the terminology.

  • An operand – is what the operator applies to. For example, in multiplication 5 * 2 there are two operands: the left operand is the number 5, and the right operand is the number 2. Sometimes operands are also called “arguments.”
  • An operator is unary if it has a single operand. For example, negation-reverses the sign of a number:


let
x = 1;

x = -x;alert( x ); // -1, unary negation is applied

An operator is binary if it has two operands. The same “minus” operator exists in the binary form:

let x = 1, y = 3;

alert( y – x ); // 2, binary subtraction subtracts the values

Formally, in the examples above we have two different operators that share the same symbol: negation (unary operator that reverses the sign) and subtraction (binary operator that performs subtraction).

COMPARISON AND EQUALITY OPERATORS

Copy to Clipboard

IMPLICIT COERCION

Javascript is a weakly typed language, we can assign a value to a variable then change its type. Image below.

Debolmente tipizzato

There are two kinds of coercion. Implicit and explicit. In explicit coercion, we are the ones asking javascript to transform a value from one type to another; the double exclamation mark !! is a type of explicit coercion which forces a value to its relative boolean value.

Coercizione implicita
Tipi di conversione

Conversion to number is done by the comparison operators, simple equality and arithmetic operators. We come to the operator + rule is that the conversion attempt to number is made. But we have an exception, if one of the two elements on which it operates + is of type string a concatenation is done by forcing the elements to the type string. This explains the cases 1. 2. 3. If, on the other hand, there is no string among the operands, conversion to number is attempted. This explains the cases 4. 5. 6.

When javascript does conversions the first thing it does is eliminate spaces, tabs, and carriage returns. This explains cases 4 through 8. There are special cases for the equality operator this happens for null and undefined. Figure below

Conversioni a number
casi speciali

EXPLICIT COERCION

The code below displays some cases of explicit coercion.

Copy to Clipboard

LOGICAL OPERATORS

Operatori logici
Copy to Clipboard

PASSAGE BY VALUE OR BY REFERENCE

By_reference_By_value

In javascriptnumber, string, boolean, null and undefined are passed by value. A change in a does not affect the value of b since the assignment let b = a creates a copy of the value of a in b. Array objects and functions are passed by reference, i.e., no copy is made but the reference is passed into memory. A change to obj1 or obj2 will reflect on each other. Figure below.

By_reference_By_value
by_reference

They return true since they share the same reference in memory.

by_reference

ARITHMETIC OPERATORS

Arithmetic operators are used to perform arithmetic operations on numbers:

Arithmetic Operators

The addition operator (+) sums the numbers:

let x = 55;
let y = 29;
let z = x + y; //Result 84

The subtraction operator () subtracts numbers.

let x = 5;
let y = 2;
let z = x – y; //Result 3

The multiplication operator (*) multiplies the numbers.

let x = 51;
let y = 20;
let z = x * y; //Result 1020

The division operator (/) divides numbers.

let x = 5;
let y = 2;
let z = x / y;
//Result 2.5

The modulo operator (%) returns the remainder of the division.

let x = 5;
let y = 2;
let z = x % y;
//Result 1

In arithmetic, division of two integers produces a quotient and a remainder. In mathematics, the result of a modulo operation is the remainder of an arithmetic division.

The increment operator (++) increments the numbers.

let x = 50;
x++;
let z = x; //z=51

The decrement operator () decrements the numbers.

let x = 50;
x–;
let z = x; //z=49

The exponentiation operator (**) elevates the first operand to the power of the second operand.

let x = 5;
let z = x ** 2; //result is 25

x ** y produces the same result as Math.pow(x,y):

PRECEDENCE AMONG OPERATORS

Operator precedence describes the order in which operations are performed in an arithmetic expression.


let
x = 1000 + 5 * 3;

Do you do addition or multiplication first? As in traditional school mathematics, multiplication is performed first. Multiplication (*) and division (/) have a higher precedence than addition (+) and subtraction (-). And (as in school mathematics) precedence can be changed using parentheses:

let x = (1000 + 5) * 3; //result is 3015

When using parentheses, operations within the parentheses are calculated first. If many operations have the same precedence (such as addition and subtraction), they are calculated from left to right:

let x = 100 + 50 – 3; //result 147

ASSIGNMENT OPERATORS

Assignment operators

Assignment operators assign values to JavaScript variables.

The assignment operator (=) assigns a value to a variable.

let x = 10;

The assignment operator += adds a value to a variable.

let x = 15;
x += 5; //x=x+5 = 20

The assignment operator -= subtracts a value from a variable.

let x = 15;
x -= 5; //x=x-5 = 10

The assignment operator *= multiplies a variable.

let x = 10;
x *= 5; //x=x*5 = 50

The assignment /= divides a variable.

let x = 15;
x /= 5; //x = x / 5 = 3

The assignment operator %= assigns a remainder to a variable.

let x = 15;
x %= 5; //x = x % 5 = 0

STRING OPERATIONS

Note that if at least one of the operands is a string, the others will also be converted to a string.

For example:

alert( ‘1’ + 2 ); // “12”

alert( 2 + ‘1’ ); // “21”

As you can see, it is not important whether the string is the first the second operand. The rule is simple: if one of the operands is a string, the others are also converted to string. However, these operations are performed from left to right, if there are two numbers before a string, first they are summed and the result converted to a string:

Now for a more complex example:

alert(2 + 2 + ‘1’ ); // “41” not “221”

Here the operations are performed one after the other, from left to right. The first + sums the two numbers and returns 4, then the next + concatenates the string 1 to the latter, so it would be like doing 4 + ‘1’ = “41.” The binary + operator is the only one that can work with strings in this way. The other arithmetic operators work only with numbers. In fact, they always convert their operands to numbers.

This is an example for subtraction and division:

alert( 6 – ‘2’ ); // 4, converts string ‘2’ to number

alert( ‘6’ / ‘2’ ); // 3, converts both operands to numbers

NUMERICAL CONVERSION UNARY OPERATOR +

The + operator exists in two forms. The binary form we used above, and the unary form. The unary + operator is applied to a single value. In case this is a number, nothing happens. If, however, it is not a number, this is converted to an operand of numeric type.

For example:

// No effect on numbers

let x = 1;

alert( +x ); //1

let y = -2;

alert( +y ); // -2

// Converts non-numeric values

alert( +true ); // 1

alert( +”” ); // 0

You get the same result as Number (…), but in a faster way. The need to convert strings to numbers arises very often. For example, if we are taking a value from an HTML field, it will usually be of type string. How to proceed in case we want to add up these values?

The binary sum would concatenate them as strings:

let apples = “2”;

let oranges = “3”;

// both values are converted to numbers before the binary sum

alert( +apples + +oranges ); // 5

// the longest variant

// alert( Number(apples) + Number(oranges) ); // 5

The operator + can also be used to add (concatenate) strings.

let text1 = “Mario”;
let text2 = “Rossi”;
let text3 = text1 + ” ” + text2; // output text3 = Mario Rossi

The assignment operator += can also be used to add (concatenate) strings:

let text1 = “Today is a beautiful “;
text1 += “day “; //text1 = Today is a beautiful day

IN-DEPTH COMPARISON OPERATORS

Comparison and logical operators are used to verify a true or false condition. Comparison operators are used in logical instructions to determine the equality or difference between variables or values.

Given that x = 5, the following table explains the comparison operators:

Comparison operators

WHERE THE COMPARISON OPERATORS ARE USED

Comparison operators can be used in conditional statements to compare values and act on the result:

if (age < 18) text =“You cannot drive.”

DEEPENING LOGICAL OPERATORS

Logical operators are used to determine the logic between variables or values. Given that x = 6 and y = 3, the following table explains the logical operators:

Logical operators

TERNARY OPERATOR

JavaScript also contains a conditional operator that assigns a value to a variable based on certain conditions.

variablename = (condition) ? value1:value2

let voteable =(age < 18) ? You can’t vote” : “You can vote“;

Comparing data of different types can yield unexpected results. When comparing a string to a number, JavaScript converts the string to a number during the comparison. An empty string is converted to 0. A non-numeric string is converted to NaN (Not a Number) which is always false.

Comparisons

When comparing two strings, “2” will be greater than“12” because (alphabetically) 1 is less than 2. To ensure a correct result, variables must be converted to the correct type before comparison:

age =Number(age);

if
(isNaN(age)) {

    voteable =“Input is not a number“;
} else {
   voteable =(age < 18 ) ? “You cannot vote” : “You can vote”;
}

TYPE OPERATORS

Type operators

BITWISE OPERATORS (BIT BY BIT)

These operators are very rarely used, when we need to work with numbers at the lowest level (bit by bit). We will not need these operators very soon, since web development makes limited use of them, but in some special areas, such as cryptography, they are useful.

BITWISE

JavaScript stores numbers as 64-bit floating-point numbers, but all bit-by-bit operations are performed on 32-bit binary numbers. Before a bit-by-bit operation is performed, JavaScript converts numbers to 32-bit signed integers. After performing the bit-by-bit operation, the result is converted back to 64-bit JavaScript numbers. A signed integer uses the leftmost bit as the minus sign.

BITWISE AND

When a bit-by-bit AND is performed on a pair of bits, returns 1 if both bits are 1.

AND

Operands are converted to 32-bit integers and expressed by a series of bits (zeros and ones). Numbers with more than 32 bits have their most significant bits discarded. For example, the following integer with more than 32 bits will be converted to a 32-bit integer:

Before:  11100110111110100000000000000110000000000001

After:                           10100000000000000110000000000001

Each bit in the first operand is associated with the corresponding bit in the second operand: first bit to first bit, second bit to second bit, and so on. The operator is applied to each pair of bits, and the result is constructed bit by bit.

9 =    00000000000000000000000000001001
14 =   00000000000000000000000000001110 
       --------------------------------
14 & 9=00000000000000000000000000001000 = 8

BITWISE OR

When a bit-by-bit OR is performed on a pair of bits, it returns 1 if one of the bits is 1:

OR
9 =    00000000000000000000000000001001
14 =   00000000000000000000000000001110
       --------------------------------
14 | 9=00000000000000000000000000001111 = 15

BITWISE XOR

When a bit-by-bit XOR is performed on a pair of bits, it returns 1 if the bits are different:

XOR
9=     00000000000000000000000000001001
14=    00000000000000000000000000001110
       --------------------------------
14 ^ 9=00000000000000000000000000000111 = 7

BITWISE NOT (~)

The NOT bit-by-bit operator (~) inverts the bits of its operand. Like other bitwise operators, it converts the operand to a 32-bit signed integer.

9 = 00000000000000000000000000001001
    --------------------------------
~9 =11111111111111111111111111110110 = -10

The 32-bit signed integer operand is inverted according to the two’s complement. That is, the presence of the most significant bit is used to express negative integers. Running the NOT bit by bit of any number x returns -(x + 1). For example, ~-5 returns 4.

LEFT SHIFT (<<)

This operator moves the first operand to the left of the specified number of bits. Excess bits shifted to the left are eliminated. Zero bits are shifted from the right.

For example, 9 << 2 returns 36:

9:     00000000000000000000000000001001
       --------------------------------
9 << 2:00000000000000000000000000100100=36 

Moving any number x to the left of y bits yields x * 2 ** y. So, for example: 9 << 3 translates to: 9 * (2 ** 3) = 9 * (8) = 72.

SIGN-PROPAGATING RIGHT SHIFT (>>)

The right shift operator (>>) shifts the first operand of the specified number of bits to the right. Excess bits shifted to the right are eliminated. Copies of the leftmost bit are shifted from the left. Since the new leftmost bit has the same value as the previous leftmost bit, the sign bit (the leftmost bit) does not change. Hence the name “sign-propagating.”

9: 00000000000000000000000000001001

--------------------------------

9 >> 2:00000000000000000000000000000010= 2

Similarly, -9 >> 2 produces -3, because the sign is preserved:

-9 :    11111111111111111111111111110111
        --------------------------------
-9 >> 2:11111111111111111111111111111101= -3 

UNSIGNED RIGHT SHIFT (>>> )

The unsigned right shift operator (>>>) (right shift of zero fill) shifts the first operand of the specified number of bits to the right. Excess bits shifted to the right are eliminated. Zero bits are shifted from the left. The sign bit becomes 0, so the result is always nonnegative. Unlike the other bit-by-bit operators, the shift to the right of zero fill returns a 32-bit unsigned integer.

9:    00000000000000000000000000001001
      --------------------------------
9>>>2:00000000000000000000000000000010= 2 

However, this is not the case with negative numbers. For example, -9 >>> 2 returns 1073741821, which is different from -9 >> 2 (which returns -3):

-9:    11111111111111111111111111110111
       --------------------------------
-9>>>2:00111111111111111111111111111101=1073741821 

LINKS TO PREVIOUS POSTS

THE JAVASCRIPT LANGUAGE

LINK TO CODE ON GITHUB

GITHUB