JavaScript: math operators.
2 min readJan 25, 2021
list of operators used in javascript and how they work.
What are operators?
- An operator is a mathematical symbol that produces a result based on two values (or variables).
- Performing math operations and calculus is a very common thing to do with any programming language.
- JavaScript offers several operators to help us perform these operations.
operators in js.
- Addition(+).
- Subtraction(-).
- Division(/).
- Remainder(%).
- Multiplication(*).
- Exponentiation(**).
- Increment(++).
- Decrement(- -).
- Unary negation(-).
- Unary plus(+).
Addition(+).
- + operator also serves as string concatenation if you use two strings.
const five = 3 + 2
const six = five+ 1
'10 ' + '10' // 1010
Subtraction(-).
const ten = 15 - 5
Division(/).
Returns the quotient of the first operator and the second:
const result = 100/ 5 //result === 2const result = 20 / 7 //result === 2.857142857142857
- if you divide by zero,JavaScript does not raise any error but returns the Infinity value (or -Infinity if the value is negative).
1 / 0 //Infinity-1 / 0 //-Infinity
Remainder(%).
- A reminder by zero is always NaN, a special value that means “Not a Number”
- gives the remainder.
const result = 20 % 5 //result === 0const result = 20 % 7 //result === 61 % 0 //NaN
-1 % 0 //NaN
Remainder(%).
- multiply two numbers.
1 * 2 //2-1 * 2 //-2
Multiplication(*).
- Raise the first operand to the power second operand.
- The ** operator is standardized across many languages including Python, Ruby, MATLAB, Lua, Perl and many others.
1 ** 2 //12 ** 1 //22 ** 2 //42 ** 8 //2568 ** 2 //64
Exponentiation(**).
- Increment a number.
- This is a unary operator, and if put before the number, it returns the value incremented.
- If put after the number, it returns the original value, then increments it.
Increment(++).
- Works like the increment operator, except it decrements the value.
let x = 0
x-- //0
x //-1
--x //-2
Decrement(- -).
- Return the negation of the operand
let x = 2-x //-2x //2
Unary negation(-).
- If the operand is not a number, it tries to convert it. Otherwise if the operand is already a number, it does nothing.
let x = 2+x //2x = '2'+x //2x = '2a'+x //NaN
If you want me to elaborate on anything or have any questions, feel free to leave me a note or contact me.