Operators
In previous examples, you have likely encountered a few operators that have fairly obvious purposes:
Many other JavaScript operators are similarly self-explanatory, though some useful ones may require additional explanation.
Arithmetic Operators
The standard arithmetic operators are
- Addition
+
- Subtraction
-
- Multiplication
*
- Division
/
Other useful arithmetic operators in JavaScript include:
- Modulo
%
(returns the remainder of dividing two numbers) - Increment
++
(increases a value by 1) - Decrement
--
(decreases a value by 1)
Order of Precedence
Remember PEMDAS from math class?
- Parentheses
- Exponents
- Multiplication
- Division
- Addition
- Subtraction
This same order of operator precedence applies in JavaScript, so be sure to construct your expressions appropriately.
const notAverage = 5 + 10 + 15 / 3; // results in 20, which is NOT the average of 5, 10, and 15
const actuallyAverage = (5 + 10 + 15) / 3; // results in 10, which IS the average of 5, 10, and 15
Assignment Operators
Assignment operators execute an arithmetic operation and new value assignment in one step. This will not work on variables declared with const
since the original value is being changed.
Other assignment operators include:
- Subtraction assignment
-=
- Multiplication assignment
*=
- Division assignment
/=
- Remainder assignment
%=
String Concatenation
When working with strings, +
is the concatenation operator, joining strings together. String concatenation is especially useful for inserting values into longer messages.
const myName = "Eric";
const welcomeMessage = "Welcome, " + myName + ".";
console.log(welcomeMessage); // logs "Welcome, Eric." to the console
When using the console with embedded CodePen examples, you should open the Pen in its own window by clicking Edit On CodePen and then clicking the Console button in the CodePen editor.
See the Pen Operators 1 (IMS322 Docs) by Eric Sheffield (@ersheff) on CodePen.
See the Pen Operators 2 (IMS322 Docs) by Eric Sheffield (@ersheff) on CodePen.