0
0
Javascriptprogramming~5 mins

Operator precedence in Javascript

Choose your learning style9 modes available
Introduction

Operator precedence tells JavaScript which part of a math or logic problem to solve first. It helps avoid confusion and mistakes.

When you write math calculations with multiple operators like +, -, *, /
When you combine logic checks like &&, ||, and ! in one statement
When you want to understand how JavaScript reads your code without extra parentheses
When debugging why a calculation or condition gives an unexpected result
Syntax
Javascript
/* Example of operator precedence in JavaScript */
let result = 3 + 4 * 2;
// Multiplication (*) happens before addition (+)
console.log(result);

Operators like * and / have higher precedence than + and -.

Use parentheses () to change the order if needed.

Examples
Multiplication happens first: 3 * 2 = 6, then 5 + 6 = 11.
Javascript
let a = 5 + 3 * 2;
console.log(a);
Parentheses change order: 5 + 3 = 8, then 8 * 2 = 16.
Javascript
let b = (5 + 3) * 2;
console.log(b);
AND (&&) has higher precedence than OR (||), so false && false = false, then true || false = true.
Javascript
let c = true || false && false;
console.log(c);
NOT (!) has highest precedence: !false = true, then true && true = true.
Javascript
let d = !false && true;
console.log(d);
Sample Program

This program shows how operator precedence affects the results of calculations and logic expressions.

Javascript
let x = 10 + 5 * 2;
let y = (10 + 5) * 2;
let z = !false || false && true;

console.log('x =', x);
console.log('y =', y);
console.log('z =', z);
OutputSuccess
Important Notes

Remember: multiplication and division happen before addition and subtraction.

Logical NOT (!) happens before AND (&&), which happens before OR (||).

Use parentheses to make your code clear and control the order explicitly.

Summary

Operator precedence decides which operations run first in expressions.

Multiplication and division have higher precedence than addition and subtraction.

Use parentheses to change or clarify the order of operations.