JavaScript arithmetic operators

Using any programming language, it is very common to perform mathematical operations and calculations. JavaScript provides a variety of operators to help us deal with numbers

Using any programming language, it is very common to perform mathematical operations and calculations.

JavaScript provides a variety of operators to help us deal with numbers.

Addition (+)

const three = 1 + 2
const four = three + 1

This+If you use strings, operators can also be used as string concatenation, so please note:

const three = 1 + 2
three + 1 // 4
'three' + 1 // three1

Subtraction (-)

const two = 4 - 2

distribution(/)

Return the quotient of the first operator and the second operator:

const result = 20 / 5 //result === 4
const result = 20 / 7 //result === 2.857142857142857

If you divide by zero, JavaScript will not raise any errors, but will returnInfinityValue (or-InfinityIf the value is negative).

1 / 0 //Infinity
-1 / 0 //-Infinity

Remaining (%)

In many use cases, the remainder is a very useful calculation:

const result = 20 % 5 //result === 0
const result = 20 % 7 //result === 6

Zero reminder is alwaysNaN, A special value that means "not a number":

1 % 0 //NaN
-1 % 0 //NaN

multiplication(*)

Multiply two numbers

1 * 2 //2
-1 * 2 //-2

Exponentiation (**)

Raise the first operand to the power of the second operand

1 ** 2 //1
2 ** 1 //2
2 ** 2 //4
2 ** 8 //256
8 ** 2 //64

Exponentiation operator**Equal to useMath.pow(), But introduce the language instead of as a library function.

Math.pow(4, 2) == 4 ** 2

This feature is a nice addition to math-intensive JS applications.

This**Operators have been standardized in multiple languages (including Python, Ruby, MATLAB, Lua, Perl, etc.).

Increment (++)

Increment a number. This is a unary operator, if it is placed before a number, it returns the incremented value.

If it is placed after the number, it will return to the original value and then increment it.

let x = 0
x++ //0
x //1
++x //2

Decrease (--)

Similar to the increment operator, but it decrements the value.

let x = 0
x-- //0
x //-1
--x //-2

Unary Negation (-)

Return the negation of the operand

let x = 2
-x //-2
x //2

One dollar plus sign (+)

If the operand is not a number, it will try to convert it. Otherwise, if the operand is already a number, no operation is performed.

let x = 2
+x //2

x = '2'
+x //2

x = '2a'
+x //NaN

Download mine for freeJavaScript beginner's manual


More js tutorials: