Performing math operations and calculus is a very common thing to do with any programming language.
- Addition (+)
- Subtraction (-)
- Division (/)
- Remainder (%)
- Multiplication (*)
- Exponentiation (**)
- Increment (++)
- Decrement (
- Unary negation (-)
- Unary plus (+)
const three = 1 + 2 const four = three + 1
+ operator also serves as string concatenation if you use strings, so pay attention:
const three = 1 + 2 three + 1 // 4 'three' + 1 // three1
const two = 4 - 2
Returns the quotient of the first operator and the second:
const result = 20 / 5 //result === 4 const result = 20 / 7 //result === 2.857142857142857
Infinity value (or
-Infinity if the value is negative).
1 / 0 - //Infinity 1 / 0 //-Infinity
The remainder is a very useful calculation in many use cases:
const result = 20 % 5 //result === 0 const result = 20 % 7 //result === 6
A remainder by zero is always
NaN, a special value that means “Not a Number”:
;(1 % 0) - //NaN (1 % 0) //NaN
Multiply two numbers
1 * 2 - //2 1 * 2 //-2
Raise the first operand to the power second operand
1 ** 2 //1 2 ** 1 //2 2 ** 2 //4 2 ** 8 //256 8 ** 2 //64
The exponentiation operator
** is the equivalent of using
Math.pow(), but brought into the language instead of being a library function.
Math.pow(4, 2) == 4 ** 2
This feature is a nice addition for math intensive JS applications.
** operator is standardized across many languages including Python, Ruby, MATLAB, Lua, Perl and many others.
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.
let x = 0 x++ //0 x //1 ++x //2
Works like the increment operator, except 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
Unary plus (+)
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 //2 x = '2' + x //2 x = '2a' + x //NaN
THE VALLEY OF CODE
THE WEB DEVELOPER's MANUAL
You might be interested in those things I do:
- Learn to code in THE VALLEY OF CODE, your your web development manual
- Find a ton of Web Development projects to learn modern tech stacks in practice in THE VALLEY OF CODE PRO
- I wrote 16 books for beginner software developers, DOWNLOAD THEM NOW
- Every year I organize a hands-on cohort course coding BOOTCAMP to teach you how to build a complex, modern Web Application in practice (next edition February-March-April-May 2024)
- Learn how to start a solopreneur business on the Internet with SOLO LAB (next edition in 2024)
- Find me on X