JavaScript: Operator precedence
Consider a simple expression:
console.log(2 + 2 * 2); // => 6The result is 6, not 8. This is explained by the concept of operator precedence in mathematics and programming. It determines the order in which operations are performed:
- Multiplication and division are performed before addition and subtraction.
- Exponentiation (
**) has an even higher precedence.
Operator precedence (from high to low):
** exponentiation
↓
* / % multiplication, division, remainder
↓
+ - addition, subtractionFor example:
console.log(2 * 2 ** 3); // => 16, because first 2 ** 3 = 8, then 8 * 2 = 16If operations with the same precedence are next to each other, they are performed from left to right:
console.log(8 / 2 * 3); // => 12, because first 8 / 2 = 4, then 4 * 3 = 12Controlling the order of operations
Sometimes you need to change the order of calculations. Parentheses are used for this. They let you specify which operations should be performed first:
console.log((2 + 2) * 2); // => 8Parentheses can be placed around any part of an expression and nested within each other:
console.log(3 ** (4 - 2)); // => 9
console.log(7 * 3 + (4 / 2) - (8 + (2 - 1))); // => 14The main rule: always close your parentheses. Unmatched parentheses cause errors: both beginners and experienced programmers sometimes forget about the closing parenthesis.
Write parentheses as a pair right away. For example, type
()and then fill in the inner part. Most code editors (including ours) automatically add the closing parenthesis as soon as you write the opening one.
Improving readability
Sometimes an expression works correctly but looks confusing. In such cases, parentheses can be added just for clarity: they won't change the result, but they will improve readability.
// Before
console.log(8 / 2 + 5 - -3 / 2); // => 10.5
// After
console.log(((8 / 2) + 5) - (-3 / 2)); // => 10.5Programs are written by people, and they are read by people too. The computer doesn't care how understandable the code is: it just needs to be syntactically correct. For a human, clear and tidy code is the key to convenience, especially when working in a team or debugging errors.
Instructions
You and 4 friends (5 people in total) ordered 2 pizzas at 300 rubles each and 4 drinks at 50 rubles each. You need to split the bill equally.
Write a one-line program with console.log(), placing parentheses so that the total amount is calculated first and then divided among everyone:
without parentheses: 2 * 300 + 4 * 50 / 5 = 640 ← incorrect
with parentheses: (2 * 300 + 4 * 50) / 5 = 160 ← correctTips
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('priority', async () => {
const consoleLogSpy = vi.spyOn(console, 'log');
await import('./index.js');
const firstArg = consoleLogSpy.mock.calls.join('\n');
expect(firstArg).toBe('160');
});Teacher's solution will be available in:
20:00
