Basic math operators
From school, we know operators. They include operations such as addition +
, multiplication *
, subtraction -
, and division /
.
In this chapter, we'll start with basic operators before focusing on JavaScript-specific features that school-level mathematics does not address.
Important Terms
Let's get familiar with some jargon before continuing.
An operand - on which operators are applied. For example: In the addition of 2 and 3, 2 & 3 are called operands.
unary - An operator is unary if it has a single operand. For example, the unary negation -
reverses the sign of a number.
let x = 2;
x = -x;
alert( x ); // x=-2
binary - An operator is binary if it has two operands. The same minus exists in binary form as well.
let x = 1, y = 4;
alert( y - x ); // 3
Math Operators
The following mathematical steps are supported:
Addition
+
,Subtraction
-
,Multiplication
*
,Division
/
,Remainder
%
,Exponentiation
**
.
You are already familiar with the above four, Let's understand Remainder %
and Exponentiation **
.
Remainder %
Despite its look, the remainder operator% has nothing to do with percents.
The result of x % y
is the remainder of the integer division of x
by y
alert( 3 % 2 ); // 1, the remainder of 3 divided by 2
alert( 9 % 3 ); // 0, the remainder of 9 divided by 3
alert( 11 % 4 ); // 3, the remainder of 11 divided by 4
Exponentiation **
It is the double asterisk**.** The exponentiation operator a ** b
raises a
the power of b
.
The actual meaning of this is a<sup>b</sup>
alert( 2 ** 1 ); // 2
alert( 2 ** 2 ); // 4
alert( 2 ** 3 ); // 8
binary + string concatenation
Let's get to know the JavaScript operators' features that go beyond basic maths.
The plus sign (+) typically adds up numbers.
However, when applied to strings, the binary + concatenates (merges) them:
let name = "Aryan" + " " + "Sharma";
alert(name); // Aryan Sharma
Note that if any of the operands is a string, then the other one is converted to a string too.
Code :
alert( '1' + 2 ); // "12"
alert( 2 + '1' ); // "21"
Question?
So, what would we get for this..🤔
alert(1 + 2 + '3' );
You might be answering 123, but let me tell you YOU are wrong❌
the correct answer is 33✅
Explanation :
So, here operators work one after another. The first +
sums two numbers, so it returns 3
, then the next +
adds the string 3
to it, so it’s like 3 + '3' = '33'
.
Now👇🏼
alert('1' + 2 + 3); // "123" and not "15"
You might be thinking, was the above example we explained wrong... No
Here, the first operand is a string, the compiler treats the other two operands as strings too. The 2
gets concatenated to '1'
, so it’s like '1' + 2 = "12"
and "12" + 3 = "123"
.
The binary +
is the only operator that supports strings in such a way. Other arithmetic operators work only with numbers and always convert their operands to numbers.
Here’s the demo for subtraction and division:
alert( 6 - '2' ); // 4, converts '2' to a number
alert( '6' / '2' ); // 3, converts both operands to numbers
There are two different versions of the plus sign: the unary form and the binary form we used previously.
Numeric conversion, unary +
The plus operator + applied to a single value, often known as the unary plus, has no effect on numbers. However, the unary addition changes the operand into a number if it is not already one.
For Example:
// Converts +ve numbers
let x = 1;
alert( +x ); // 1
// Converts -ve numbers
let y = -5;
alert( +y ); // -5
// Converts non-numbers
alert( +true ); // 1
alert( +false); // 0
alert( +"" ); // 0
It actually does the same thing as Number(...)
, but is shorter.
The need to convert strings to numbers arises very often. For example, if we are getting values from HTML form fields, they are usually strings. What if we want to sum them?
The binary plus would add them as strings:
let apples = "3";
let mangoes = "4";
alert( apples + mangoes ); // "34", the binary plus concatenates strings
It does the same thing as what concat
does.
Now, if we want to add values of apples
and mangoes
as numbers, then:
let apples = "3";
let mangoes = "4";
// both values converted to numbers before the binary plus
alert( +apples + +mangoes ); // 7
A Programmer's standout +
carries more importance than a Mathematical one cares.
Operator precedence
If an expression contains more than one operator, their precedence, or the default priority order of operators, determines the execution order.
Precedence | Name | Sign |
… | … | … |
14 | unary plus | + |
14 | unary negation | - |
13 | exponentiation | ** |
12 | multiplication | * |
12 | division | / |
11 | addition | + |
11 | subtraction | - |
... | ... | ... |
2 | assignment | = |
... | ... | ... |
Assignment
Let’s note that an assignment =
is also an operator. It is listed in the precedence table with the very low priority of 2
.
That’s why, when we assign a variable, like x = 2 * 2 + 1
, the calculations are done first and then the =
is evaluated, storing the result in x
.
let x = 2 * 2 + 1;
alert( x ); // 5
Returns a value
The fact that = is an operator rather than a "magical" language construct has an interesting significance.
In JavaScript, all operators yield a value. This is evident for + and -, but it also applies to =.
The x = value function writes the value into x and then returns it.
let a = 1;
let b = 2;
let c = 3 - (a = b + 1);
alert( a ); // 3
alert( c ); // 0
In the above example, the result of the expression (a = b + 1) is the value provided to a (that is, 3). It is then used for additional evaluations.
Isn't that a strange code? We should grasp how it works because we see it in JavaScript libraries from time to time.
However, please do not write the code in this manner. Such tricks do not make code more clear or readable.
Chaining assignments
Let's understand what chaining is.
let a = b = 1;
alert(a); //1
alert(b); //1
Chained Assignments evaluate from right to left. First b is valued as 1 then a.
Modify-in-place
We frequently need to apply an operator to a variable and save the resulting value in the same variable.
Let's see:
let a = 2;
a = a + 5;
a = a * 2;
This notation can be shortened using the operators +=
and *=
:
let a = 2;
a += 5; // a = 7
a *= 2; // a = 14
alert( a ); // 14
Increment/decrement
Decreasing or Increasing a variable by 1 finds a lot of its use in programming
Increment
++
increases a variable by 1:let counter = 2; counter++; //counter = counter + 1 alert( counter ); // 3
Decrement
--
decreases a variable by 1:let counter = 2; counter--; // counter = counter - 1 alert( counter ); // 1
The operators ++
and --
can be placed either before or after a variable.
When the operator goes after the variable, it is in “postfix form”:
counter++
.The “prefix form” is when the operator goes before the variable:
++counter
.
For Instance:
Prefix
let counter = 1;
alert( 2 * ++counter ); // 4
Postfix
let counter = 1;
alert( 2 * counter++ ); // 2
value of counter will update later the step it is used with ++ in postfix
alert( counter ); // 4
Bitwise operators
Bitwise operators operate on the binary representation of the arguments as 32-bit integer numbers.
These operators are not exclusive to JavaScript. They are supported by the majority of programming languages.
Some of the operators are :
AND (
&
)OR (
|
)XOR (
^
)NOT (
~
)LEFT SHIFT (
<<
)RIGHT SHIFT (
>>
)ZERO-FILL RIGHT SHIFT (
>>>
)
Comma
The comma operator ,
is one of the rarest and most unusual operators. Sometimes, it’s used to write shorter code, so we need to know it in order to understand what’s going on.
The comma operator allows us to evaluate several expressions, dividing them with a comma ,
. Each of them is evaluated but only the result of the last one is returned.
let a = (1 + 2, 3 + 4);
alert( a ); // 7 the result of ( 3,7 )
Sometimes, people use it in more complex constructs to put several actions in one line.
for (a = 1, b = 3, c = a * b; a < 10; a++) {
...
}
That's all but wait.... We have some tasks for you!!
TASKS
What are the final values of all variables a
, b
, c
and d
after the code below?
let a = 1, b = 1;
let c = ++a; // ?
let d = b++; // ?
What are the values of a
and x
after the code below?
let a = 2;
let x = 1 + (a *= 2);
What are results of these expressions?
"" + 1 + 0
"" - 1 + 0
true + false
6 / "3"
"2" * "3"
4 + 5 + "px"
"$" + 4 + 5
"4" - 2
"4px" - 2
" -9 " + 5
" -9 " - 5
null + 1
undefined + 1
" \t \n" - 2