JavaScript Operators: Arithmetic, Assignment, Comparison, Logical and More
Operators are the verbs of a programming language: they add prices, compare a status code with 200, combine conditions and pick between two values. You have already met a few; in this lesson you will learn every JavaScript operator you need in real code and tests, how short-circuit evaluation works, how i++ differs from ++i, and how precedence decides what runs first.
📖 What You’ll Learn: arithmetic operators including % and **, increment and decrement, assignment and compound assignment, comparison operators, logical operators and short-circuiting, the conditional (ternary) operator, typeof, instanceof, in, delete, spread, the comma operator, and operator precedence.
➕ Arithmetic Operators
Definition: an operator is a symbol that performs an operation on one or more values, called operands. a + b has two operands (a binary operator); -a has one (a unary operator).
📄 arithmetic.js
const a = 17, b = 5;
console.log("a + b =", a + b);
console.log("a - b =", a - b);
console.log("a * b =", a * b);
console.log("a / b =", a / b); // always a decimal division
console.log("a % b =", a % b); // remainder
console.log("a ** 2 =", a ** 2); // exponent (power)
console.log("-a =", -a); // unary minus
⌨️ Terminal
node arithmetic.js
🖥️ Output
a + b = 22
a - b = 12
a * b = 85
a / b = 3.4
a % b = 2
a ** 2 = 289
-a = -17
/never rounds:17 / 5is3.4. UseMath.floor(a / b)orMath.truncfor whole-number division.%(remainder) is handy for even/odd checks (n % 2 === 0) and for cycling through values.+also joins strings, as you saw in the Type Conversion lesson.
📄 remainder.js
const seconds = 3725;
const h = Math.floor(seconds / 3600);
const m = Math.floor((seconds % 3600) / 60);
const s = seconds % 60;
console.log(`${seconds}s = ${h}h ${m}m ${s}s`);
for (let n = 1; n <= 4; n++) {
console.log(n, n % 2 === 0 ? "even" : "odd");
}
⌨️ Terminal
node remainder.js
🖥️ Output
3725s = 1h 2m 5s
1 odd
2 even
3 odd
4 even
🔼 Increment and Decrement (++ and –)
++ adds 1 and -- subtracts 1. The position matters when you use the result in the same expression:
- Postfix
x++: returns the old value, then increments. - Prefix
++x: increments first, then returns the new value.
📄 increment.js
let count = 5;
console.log(count++); // returns 5, then count becomes 6
console.log(count);
console.log(++count); // count becomes 7, returns 7
console.log(count--); // returns 7, then count becomes 6
console.log(count);
⌨️ Terminal
node increment.js
🖥️ Output
5
6
7
7
6
💡 Tip: On its own line (count++;) prefix and postfix behave the same. Avoid using ++ inside larger expressions; count += 1 on its own line is clearer.
📝 Assignment Operators
= assigns a value. Compound assignment operators combine an operation with assignment:
| Operator | Example | Same as |
|---|---|---|
+= | x += 5 | x = x + 5 |
-= | x -= 2 | x = x - 2 |
*= | x *= 3 | x = x * 3 |
/= | x /= 2 | x = x / 2 |
%= | x %= 3 | x = x % 3 |
**= | x **= 2 | x = x ** 2 |
??=, ||=, &&= | x ??= 1 | Logical assignment (see the previous lesson) |
📄 assignment.js
let total = 100;
total += 50; // 150
total -= 20; // 130
total *= 2; // 260
total /= 4; // 65
total %= 10; // 5
total **= 3; // 125
console.log(total);
let report = "Results:";
report += " 18 passed,";
report += " 2 failed";
console.log(report);
⌨️ Terminal
node assignment.js
🖥️ Output
125
Results: 18 passed, 2 failed
⚖️ Comparison Operators
Comparison operators return true or false:
| Operator | Meaning | Example (true) |
|---|---|---|
=== | Strictly equal (same type and value) | 200 === 200 |
!== | Strictly not equal | "200" !== 200 |
== / != | Loosely equal / not equal (with coercion) | Avoid; see the Equality lesson |
> < | Greater / less than | 5 > 3 |
>= <= | Greater / less than or equal | 3 <= 3 |
📄 comparison.js
const status = 201;
const responseMs = 850;
const limitMs = 1000;
console.log("success:", status >= 200 && status < 300);
console.log("fast enough:", responseMs <= limitMs);
console.log("created:", status === 201);
console.log("not an error:", status !== 500);
⌨️ Terminal
node comparison.js
🖥️ Output
success: true
fast enough: true
created: true
not an error: true
🧠 Logical Operators and Short-Circuiting
| Operator | Name | Result |
|---|---|---|
a && b | AND | If a is falsy, returns a; otherwise returns b |
a || b | OR | If a is truthy, returns a; otherwise returns b |
!a | NOT | true if a is falsy, otherwise false |
a ?? b | Nullish coalescing | b only if a is null/undefined |
With booleans they work as you expect. Note that && and || return one of the operand values, not necessarily true or false:
📄 logical.js
const isLoggedIn = true;
const isAdmin = false;
console.log(isLoggedIn && isAdmin); // false
console.log(isLoggedIn || isAdmin); // true
console.log(!isAdmin); // true
console.log("Asha" && "admin"); // both truthy: returns the second value
console.log("" || "default name"); // first is falsy: returns the second
console.log(0 && "never checked"); // first is falsy: returns 0
⌨️ Terminal
node logical.js
🖥️ Output
false
true
true
admin
default name
0
Short-circuit evaluation: JavaScript stops evaluating as soon as the result is known. The right side of && runs only if the left is truthy; the right side of || runs only if the left is falsy.
📄 short-circuit.js
function sendReport() {
console.log("report sent");
return true;
}
const failures = 0;
failures > 0 && sendReport(); // left is false: sendReport never runs
failures === 0 || sendReport(); // left is true: sendReport never runs
console.log("done, no report needed");
const user = null;
console.log(user && user.name); // safe: stops at null
⌨️ Terminal
node short-circuit.js
🖥️ Output
done, no report needed
null
⚠️ Watch out: Do not use && as a hidden if in team code (isValid && save()); a real if statement is easier to read and debug. Use the operators for conditions and defaults.
❓ The Conditional (Ternary) Operator
Definition: the conditional operator condition ? valueIfTrue : valueIfFalse is the only operator with three operands, so it is often called the ternary operator. It is an expression, so it produces a value you can store or print.
📄 ternary.js
const score = 72;
const result = score >= 60 ? "PASS" : "FAIL";
console.log(`Score ${score}: ${result}`);
const items = 1;
console.log(`${items} ${items === 1 ? "item" : "items"} in cart`);
const ms = 1530;
const label = ms < 500 ? "fast" : ms < 1000 ? "ok" : "slow"; // chained
console.log(`${ms} ms is ${label}`);
⌨️ Terminal
node ternary.js
🖥️ Output
Score 72: PASS
1 item in cart
1530 ms is slow
💡 Tip: One level of ternary is readable; chained ternaries quickly become hard to follow. For three or more branches, use if...else if (next lesson) or a lookup object.
🔎 typeof, instanceof, in and delete
📄 keyword-ops.js
class LoginPage {}
const page = new LoginPage();
const user = { name: "Asha", role: "tester" };
console.log(typeof user.name); // type of a value
console.log(page instanceof LoginPage); // created by this class?
console.log([] instanceof Array);
console.log("role" in user, "email" in user); // does the property exist?
console.log(0 in ["a"], 1 in ["a"]); // index exists in array?
delete user.role; // remove a property
console.log(user);
⌨️ Terminal
node keyword-ops.js
🖥️ Output
string
true
true
true false
true false
{ name: 'Asha' }
typeofreturns a type name as a string (covered in the Data Types lesson).instanceofchecks whether an object was created by a class or constructor.inchecks whether a property name (or array index) exists, even if its value isundefined.deleteremoves a property from an object. It does not work on variables.
🌊 Spread (…) and the Comma Operator
The spread syntax ... expands an array or object into individual elements. You will use it constantly; the Destructuring and Spread lesson covers it fully.
📄 spread.js
const smoke = ["login", "search"];
const regression = [...smoke, "checkout", "refund"];
console.log(regression);
console.log(Math.max(...[12, 99, 45]));
const defaults = { browser: "chromium", headless: true };
const config = { ...defaults, headless: false };
console.log(config);
⌨️ Terminal
node spread.js
🖥️ Output
[ 'login', 'search', 'checkout', 'refund' ]
99
{ browser: 'chromium', headless: false }
The comma operator evaluates several expressions and returns the last one. You will mostly see it in for loops that update two variables:
📄 comma.js
for (let i = 0, j = 4; i < j; i++, j--) {
console.log(i, j);
}
⌨️ Terminal
node comma.js
🖥️ Output
0 4
1 3
📐 Operator Precedence
Definition: precedence decides which operator runs first when an expression has several. Higher precedence runs first; operators with the same precedence run left to right (except ** and assignment, which run right to left).
| Order | Operators |
|---|---|
| 1 (highest) | ( ) grouping |
| 2 | ?., member access . [ ], function call ( ), new |
| 3 | Postfix x++ x-- |
| 4 | Unary ! - + ++x typeof delete |
| 5 | ** |
| 6 | * / % |
| 7 | + - |
| 8 | < > <= >= in instanceof |
| 9 | === !== == != |
| 10 | && |
| 11 | || ?? |
| 12 | ? : |
| 13 (lowest) | Assignment = += … and the comma , |
📄 precedence.js
console.log(2 + 3 * 4); // * first: 14
console.log((2 + 3) * 4); // grouping first: 20
console.log(2 ** 3 ** 2); // right to left: 2 ** 9 = 512
console.log(10 - 4 - 3); // left to right: 3
console.log(true || false && false); // && first: true
console.log(!0 + 1); // !0 is true, true + 1 = 2
⌨️ Terminal
node precedence.js
🖥️ Output
14
20
512
3
true
2
💡 Tip: You do not need to memorise the table. When in doubt, add parentheses: (price * qty) + shipping is clear to every reader.
📝 Practice Questions with Answers
Try each question on your own first, then open the answer to check your work. Run the code with node practice.js.
Q1. Print the total price of 3 items at 249.5 each, plus 18% tax, rounded to two decimals.
Show answer
📄 practice1.js
const subtotal = 3 * 249.5;
const total = subtotal + subtotal * 0.18;
console.log(total.toFixed(2));🖥️ Output
883.23Q2. Predict the output, then run it.
let x = 3;
const y = x++ + ++x;
console.log(x, y);Show answer
📄 practice2.js
let x = 3;
const y = x++ + ++x;
console.log(x, y);🖥️ Output
5 8x++ returns 3 and makes x 4; ++x then makes x 5 and returns 5. So y = 3 + 5 = 8 and x is 5.
Q3. Use the remainder operator to print Fizz for multiples of 3 between 1 and 10, and the number otherwise.
Show answer
📄 practice3.js
for (let n = 1; n <= 10; n++) {
console.log(n % 3 === 0 ? "Fizz" : n);
}🖥️ Output
1
2
Fizz
4
5
Fizz
7
8
Fizz
10Q4. A test passes if the status is 200 and the response time is under 2000 ms, or if the status is 304. Write the condition and test it with (200, 1500), (200, 2500) and (304, 3000).
Show answer
📄 practice4.js
const passed = (status, ms) => (status === 200 && ms < 2000) || status === 304;
console.log(passed(200, 1500));
console.log(passed(200, 2500));
console.log(passed(304, 3000));🖥️ Output
true
false
trueThe parentheses are not strictly needed (&& has higher precedence than ||) but make the intent clear.
Q5. Use a ternary to print 1 test failed or N tests failed for 1 and 4 failures.
Show answer
📄 practice5.js
for (const failed of [1, 4]) {
console.log(`${failed} ${failed === 1 ? "test" : "tests"} failed`);
}🖥️ Output
1 test failed
4 tests failedQ6. Check whether the object { id: 7, email: undefined } has an email property and a phone property, using in. Then explain why user.email !== undefined gives a different answer.
Show answer
📄 practice6.js
const user = { id: 7, email: undefined };
console.log("email" in user, "phone" in user);
console.log(user.email !== undefined);🖥️ Output
true false
falsein checks whether the property exists. email exists but holds undefined, so comparing its value says “no value”, while in says “the key is there”.
🧠 MCQ Quiz: Operators
10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.
- What is
17 % 5?Answer: 2. % returns the remainder: 17 = 3 × 5 + 2. - What is
2 ** 3?Answer: 8. ** is the exponent operator: 2 × 2 × 2. - After
let a = 5; const b = a++;, what are a and b?Answer: a = 6, b = 5. Postfix returns the old value before incrementing. - What does
"" || "guest"return?Answer:"guest". || returns the first truthy operand, or the last one. - What does
"a" && "b"return?Answer:"b". && returns the last operand if all are truthy. - In
x > 0 && save(), when issave()called?Answer: Only when x > 0 is true. Short-circuit: the right side runs only if the left side is truthy. - What is
2 + 3 * 4?Answer: 14. * has higher precedence than +. - What is
2 ** 3 ** 2?Answer: 512. ** is right-associative: 2 ** (3 ** 2) = 2 ** 9. - Which operator checks if a property name exists in an object?Answer:
in."key" in objreturns true even if the value is undefined. - What does
score >= 50 ? "pass" : "fail"return when score is 50?Answer:"pass". 50 >= 50 is true, so the first value is returned.
💼 Interview Questions and Answers
Q1. What is the difference between x++ and ++x?
Both add 1 to x. Postfix x++ evaluates to the value before the increment; prefix ++x evaluates to the value after. The difference only matters when the expression’s value is used, for example const y = x++. As a standalone statement they are identical.
Q2. What is short-circuit evaluation, and how is it used?
&& stops at the first falsy operand and || stops at the first truthy operand, without evaluating the rest. It is used for guards (user && user.name), defaults (name || "guest", better ?? when 0 or “” are valid), and to avoid unnecessary work. It also means function calls on the right side may never run, which matters if they have side effects.
Q3. Do && and || always return booleans?
No. They return one of their operands. "a" && 0 returns 0; null || "x" returns "x". Only ! always returns a boolean. Use Boolean(a && b) or !!(a && b) when you need a real boolean, for example for an API flag.
📄 returns.js
console.log("a" && 0, null || "x", !!("a" && "b"));
⌨️ Terminal
node returns.js
🖥️ Output
0 x true
Q4. When would you use the ternary operator instead of if/else?
When choosing between two values in an expression: a label, a plural form, a default inside a template literal or JSX. Use if/else when you need to run statements (several lines, side effects) or when there are more than two branches. Nested ternaries hurt readability and are often blocked by lint rules.
Q5. What is operator precedence and associativity? Give an example where it causes a bug.
Precedence decides which operator binds first; associativity decides the order for operators of equal precedence. A common bug: "Total: " + price + tax joins strings left to right, giving "Total: 10020" instead of "Total: 120". Grouping fixes it: "Total: " + (price + tax), or use a template literal `Total: ${price + tax}`.
📄 precedence-bug.js
const price = 100, tax = 20;
console.log("Total: " + price + tax);
console.log("Total: " + (price + tax));
⌨️ Terminal
node precedence-bug.js
🖥️ Output
Total: 10020
Total: 120
❓ Frequently Asked Questions
🤔 What are the types of operators in JavaScript?
Arithmetic (+ - * / % **), assignment (= += -= …), comparison (=== !== > <), logical (&& || ! ??), the conditional (ternary) operator, and special operators such as typeof, instanceof, in, delete, spread and comma.
🤔 What does the % operator do in JavaScript?
It returns the remainder of a division. 10 % 3 is 1. It is commonly used to test even or odd numbers and to wrap values around.
🤔 Is there an integer division operator?
No. / always produces a decimal result. Use Math.floor(a / b) (or Math.trunc for negative numbers) to get the whole-number part.
🤔 What is the ?: operator called?
The conditional operator, usually called the ternary operator because it takes three operands: condition ? a : b.
🏁 Summary
- Arithmetic:
+ - * / % **;/never rounds and%gives the remainder. x++returns the old value,++xthe new one; compound assignment (+=…) updates in place.- Comparisons return booleans; use
===and!==. &&and||short-circuit and return an operand value; the ternary picks between two values.typeof,instanceof,in,deleteand spread are operators too; use parentheses when precedence is unclear.
Next, continue with Lesson 13: if, else if, else. For extra practice, solve the JavaScript operators practice programs.
🎬 Watch JavaScript and automation tutorials on YouTube!
Subscribe to SqaToolsByDY • Practice on sqatools.in