What is true + true + true * 3 in JavaScript?
JavaScript is a dynamic and flexible programming language, often surprising developers with its type coercion and operator precedence. One expression that might puzzle beginners (or even some experienced developers) is true + true + true * 3. Let’s break this down to understand what’s really happening behind the scenes.
The expression: true + true + true * 3
At first glance, this might seem like a simple addition, but JavaScript’s rules of operator precedence and type conversion (coercion) are at play. Here’s how it works step-by-step:
1. Operator Precedence
The first thing to understand is JavaScript’s order of operations (also known as operator precedence). Like most programming languages, JavaScript follows certain rules about which operators should be evaluated first:
- Multiplication (
*) has a higher precedence than addition (+). - Therefore, JavaScript will perform the multiplication part of the expression first, followed by the additions.
2. Type Coercion
In JavaScript, true is a boolean value, but when it is involved in an arithmetic operation like addition or multiplication, it gets automatically converted to a number. This process is called type coercion.
trueis coerced to1.falseis coerced to0.
This is important because, during evaluation, true will act like 1 in mathematical operations.
Step-by-Step Breakdown
Let’s evaluate the expression true + true + true * 3:
- First, we look at the multiplication part:
true * 3.trueis coerced to1, so1 * 3 = 3.
true + true + 3
- Next, we move on to the addition. Start with the first part:
true + true.
Again,trueis coerced to1, so1 + 1 = 2.
Now, the expression becomes:
2 + 3
- Finally, we perform the last addition:
2 + 3 = 5.
Conclusion: The Result is 5
So, the final result of the expression true + true + true * 3 is 5.
Why Does This Happen?
To sum it up:
- Operator Precedence ensures that multiplication happens before addition.
- Type Coercion automatically converts the boolean
trueinto the number1, which makes it participate in the arithmetic operations.
If you want to avoid confusion like this in your code, you can use parentheses to make the order of operations clear:
(true + true + true) * 3
In this case, the result would be 9 because the addition happens first, followed by multiplication.
Final Thoughts
JavaScript’s behavior with booleans, numbers, and operator precedence might seem tricky at first, but with a solid understanding of how the language handles type coercion and operations, you’ll be able to predict and control how expressions are evaluated. Always keep an eye on the precedence and, when in doubt, use parentheses to clarify your intentions!
