Let’s start with arithmetic operators.
These are the arithmetic operators they don’t teach you right out of the gate. That is, everything other than the basic
* ). They’re really useful, but not obviously so to a newcomer.
First things first, vocabulary:
A symbol denoting an operation.
An action or procedure which produces a new value from zero or more input values.
The object of an operation, a variable or expression on which an operation is performed.
Cool. Now we all know that an operator performs an operation upon an operand. Words are fun but let’s get on to the operators!
% The Remainder Operator
Otherwise known as the modulo or modulus. There will most certainly come a time when you need to utilize the remainder of some quotient in your code. If you find yourself writing a little helper function to do that, stop. Remember the modulo! It’s super useful.
- Unary Operators (negation/plus)
This is not addition and subtraction. Unary operators always prefix their operands. Both operators can convert non numbers into numbers. Unary negation is basically like slapping a negative onto it’s operand.
The unary plus operator is a great way to convert a string to a number. It is the fastest way, and in many cases is a good replacement for
parseFloat(). It’s syntactically beautiful because it’s so minimal. It can handle integers, floats, and positive hexadecimal numbers.
Note: Unary plus will return
NaN if its operand is not completely numeric.
-- Increment/Decrement (prefix/postfix)
These last two are common. Most people know them as soon as they learn about
for loops. They do what you would expect—increment or decrement their operands by one integer. Note: this works the same whether the operand is an integer or a floating point number.
The cool (and useful) behavior to be aware of here, has to do with whether they are prefixed or post. Regardless of pre vs post, they will always carry out the same operation. However, they can be very useful in logical evaluations where their operands are both evaluated and incremented or decremented.
Recognize that when
x is evaluated at the top of the first loop, it is first evaluated and then decremented. In the second loop, the decrementing happens first. It never logs zero because
y’s value becomes zero before it’s third evaluation, and once it does, it also becomes falsy at which point the loop breaks.
If you’re just starting out with programming, getting comfortable with these operators will make coding a lot more fun and you will be just a bit more capable. There are many scenarios where you can employ them.
Up Next: Accessors