Javascript let result = 5 + 3 * 2;
console.log(result); // Output: 11
Example 1 Basic Arithmetic
Javascript let result = 5 + 3 * 2; console.log(result); // Output: 11Here’s the breakdown:
- The
*(multiplication) operator has higher precedence than+(addition), so JavaScript will evaluate3 * 2first, resulting in6. - Then, it evaluates
5 + 6, which results in11.
Even though the expression goes left-to-right for addition and multiplication, operator precedence affects the order in which operations occur.
Example 2: Assignment with Multiple Operations
javascript
let x = 2;
let y = 3;
let result = x + y * 4 - 1;
console.log(result); // Output: 13
- First,
y * 4is evaluated (left-to-right) because multiplication has higher precedence than addition and subtraction, giving12. - Then,
x + 12is calculated (left-to-right), which is2 + 12 = 14. - Finally,
14 - 1is calculated, resulting in13.
Example 3: Logical Operators
JavaScript also evaluates logical operators left to right:
javascript
let a = true;
let b = false;
let result = a && b || true;
console.log(result); // Output: true
- First,
a && bis evaluated (left-to-right), which results infalsebecausebisfalse. - Then,
false || trueis evaluated, which results intrue.
Example 4: Chaining Assignments
javascriptlet x = 5;
let y = x = 10;
console.log(x); // Output: 10
console.log(y); // Output: 10
Here, the assignment is evaluated left-to-right:
x = 10is executed first, soxbecomes10.- Then,
y = 10is executed, soyalso gets the value10.
No comments:
Post a Comment