Javascript
let result = 5 + 3 * 2;
console.log(result); // Output: 11
Here’s the breakdown:
- The
*
(multiplication) operator has higher precedence than+
(addition), so JavaScript will evaluate3 * 2
first, 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 * 4
is evaluated (left-to-right) because multiplication has higher precedence than addition and subtraction, giving12
. - Then,
x + 12
is calculated (left-to-right), which is2 + 12 = 14
. - Finally,
14 - 1
is 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 && b
is evaluated (left-to-right), which results infalse
becauseb
isfalse
. - Then,
false || true
is 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 = 10
is executed first, sox
becomes10
.- Then,
y = 10
is executed, soy
also gets the value10
.
No comments:
Post a Comment