Arithmetic Operators
This Scrimba screencast was created by Dylan C. Israel.
As the name suggests, arithmetic operators perform arithmetic on numbers or variable assigned a number. Common JavaScript operators includes addition (+
), subtraction (-
), multiplication (*
) and division (/
).
When working with arithmetic operators, typically two numbers, variables, or expressions are required.
const a = 3
const b = 5
const add = 100 + 50 // 150
const multiply = a * b // 15
However, these operations can be part of a larger expression
const a = 3
const b = 5
const expression = (100 + 50) * a // 450
TIP
When working with multiple arithmetic operators in JavaScript, the orders of operation (PEMDAS) will be followed.
Parentheses, Exponents, Multiplication and Division, and Addition and Subtraction
The Modulus Operator
The modulus operator (%
) returns the division remainder.
const a = 3
const b = 5
const modulus = b % a // 2 - 3 goes into 5 one time with a reminder of 2
Incrementing and Decrementing
The need increment a number by 1 or decrement a number by 1 occur so often in programming that there are special operators for those tasks.
The increment operator (++
) increments numbers by 1
let a = 3 // Note: let is used here because the value of a will change
a++
console.log(a) // 4
The decrement operator (--
) decrements numbers by 1.
let b = 5 // Note: let is used here because the value of b will change
b--
console.log(b) // 4
The increment and decrement operators can be used in two forms postfix and prefix.
let a = 3
a++ // postfix
++a // prefix
Both forms will increment or decrement the value of the variable, but value returned maybe different.
The postfix form returns the original value of the variable before the increment or decrement occurs.
let a = 3
console.log(a++) // 3
The prefix form returns the value after the increment or decrement occurs.
let a = 3
console.log(++a) // 4