Learn JavaScript · lesson 8 of 60 · about 6 minutes
Precedence and Updates
Count likes on Sam's page with ++ and +=, and predict the order JavaScript works sums out.
What you'll learn
- Apply operator precedence
- Use brackets to control order
- Update values with ++, --, += and friends
Counting likes
Sam's page gets a like counter. Every like means likes = likes + 1, written out in full every time. Counting is so common that JavaScript has shortcuts:
likes += 5meanslikes = likes + 5; there's also-=,*=and/=likes++adds 1, andlikes--takes 1 away
They change the variable, so it has to be made with let.
Step through the likes
let likes = 10;
likes += 5;
likes *= 2;
likes--;
console.log(likes);Output
29Order of operations
When a line has several operators, JavaScript follows the same order as maths:
1. Brackets
2. **
3. *, / and %
4. + and -
Operators on the same level go left to right.
Brackets change the answer
console.log(2 + 3 * 4);
console.log((2 + 3) * 4);
console.log(20 - 6 / 2);Output
14
20
17Tip
A const can't be updated, not even with ++. Try it and JavaScript stops with TypeError: Assignment to constant variable.
Now try it yourself
This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.