JavaScript: Operators
In mathematics and programming, we often use operation signs such as +, -, *, and others. In programming, such signs are called operators.
- An operator is a symbol or word that denotes an action.
- Operands are the values to which the operator is applied.
Example:
console.log(8 + 2);Here:
+is an operator8and2are operands- the result will be
10
operand operator operand result
8 + 2 → 10
5 - 3 → 2
4 * 3 → 12Unary operators
There are also unary operations that work with a single operand. Example:
console.log(-3); // => -3In this case, - is a unary operator, and 3 is the operand. The interpreter receives the command: "take the number 3 and change its sign".
The - operator can be used in different ways. When it stands between two numbers, it is a subtraction operation:
console.log(5 - 2); // => 3
console.log(10 - 7); // => 3This difference is especially noticeable when working with negative numbers:
// minus times minus gives plus
console.log(5 - -2); // => 7First we see the subtraction operation: 5 - (...). But on the right there is a unary minus -2, which turns 2 into a negative number. As a result, we get: 5 - (-2) = 7.
Thus, the meaning of - depends on the context: if there is another number next to it, it is subtraction; otherwise, it is a change of the number's sign.
Errors in calculations
If you treat -3 as a single number, you might not notice that - is a separate operator with its own priority. For example:
console.log(-3 ** 2); // => -9, not 9!At first glance, it might seem that -3 is being squared, and the result should be 9. But the result will be -9.
The reason lies in the order of calculations: first the exponentiation (**) is performed, and only then the unary minus is applied. That is: -(3 ** 2) = -9. We will talk about operator priority in more detail in the following lessons.
Instructions
A submarine is at a depth of -81 m. The deck of the rescue ship is located at a height of +6 m above the water level.
Calculate and print to the screen:
- The total ascent distance in meters.
- The ascent time in minutes — the submarine rises at a speed of 3 m/min.
Tips
Always separate arithmetic operators from their operands with spaces — this is good programming style.
If you've reached a deadlock it's time to ask your question in the «Discussions». How ask a question correctly:
- Be sure to attach the test output, without it it's almost impossible to figure out what went wrong, even if you show your code. It's complicated for developers to execute code in their heads, but having a mistake before their eyes most probably will be helpful.
Your exercise will be checked with these tests:
// @ts-check
import { expect, test, vi } from 'vitest';
test('operator', async () => {
const consoleLogSpy = vi.spyOn(console, 'log');
await import('./index.js');
const firstArg = consoleLogSpy.mock.calls.join('\n');
expect(firstArg).toBe('87\n29');
});Teacher's solution will be available in:
20:00
