What are JavaScript operators (arithmetic, logical,
comparison)?
JavaScript operators are special symbols used to perform operations on one or
more values (operands) and return a result. They are fundamental building blocks of
any JavaScript program, allowing you to perform calculations, compare values,
assign variables, and control program flow.
Operators are categorized based on the type of operation they perform.
Understanding these categories is essential for writing effective and efficient
JavaScript code.
Definition: An operator in JavaScript is a symbol that tells the JavaScript engine
to perform some operation, such as mathematical calculations, assignment,
comparison, or logical operations, on values or variables.
Core Categories of Operators
While there are many types of operators in JavaScript (assignment, bitwise, unary,
etc.), the most commonly used and fundamental ones are arithmetic, logical, and
comparison operators.
1. Arithmetic Operators
Arithmetic operators are used to perform mathematical calculations on numbers.
They work similar to arithmetic operations in mathematics.
Operator Description Example Result
+ Addition (also string concatenation) 5 + 3 8
- Subtraction 10 - 4 6
* Multiplication 6 * 2 12
/ Division 15 / 3 5
% Modulus (remainder of division) 10 % 3 1
Operator Description Example Result
** Exponentiation (ES2016) 2 ** 3 8
++ Increment (adds 1) let x = 5; x++; x is now 6
-- Decrement (subtracts 1) let y = 5; y--; y is now 4
Arithmetic Operators Example
JavaScript
let a = 10;
let b = 3;
console.log(`a + b = ${a + b}`); // 13
console.log(`a - b = ${a - b}`); // 7
console.log(`a * b = ${a * b}`); // 30
console.log(`a / b = ${a / b}`); // 3.333...
console.log(`a % b = ${a % b}`); // 1
console.log(`a ** 2 = ${a ** 2}`); // 100
let counter = 0;
counter++; // counter is now 1 (postfix increment)
++counter; // counter is now 2 (prefix increment)
console.log(counter); // 2
Important Note on +: If one of the operands is a string, the + operator performs
string concatenation instead of addition. This is a common source of bugs if not
understood.
JavaScript
console.log("Hello " + "World"); // "Hello World"
console.log("Number: " + 10); // "Number: 10"
2. Logical Operators
Logical operators are used to combine or manipulate boolean (true/false) values.
They are essential for controlling program flow in conditional statements and loops.
Operator Description Example Result
(true &&
Logical AND: Returns true if both operands are truthy.
false) false
&& Otherwise, returns the first falsy operand or the last
(5 > 3 && true
operand.
10 < 20)
(true ||
Logical OR: Returns true if at least one operand is
false) true
|| truthy. Otherwise, returns the first truthy operand or
(0 || "hello"
the last operand.
"hello")
!true false
! Logical NOT: Inverts the boolean value of its operand.
!(5 > 3) false
Nullish Coalescing (ES2020): Returns the right-hand null ??
"default"
?? operand when the left-hand operand is null or "default"
0
undefined. Otherwise, returns the left-hand operand. 0 ?? 100
Logical Operators Example
JavaScript
let age = 25;
let hasLicense = true;
// Logical AND (&&)
if (age >= 18 && hasLicense) {
console.log("Eligible to drive."); // This will execute
}
// Logical OR (||) - often used for default values
let username = "";
let defaultName = "Guest";
let displayUser = username || defaultName;
console.log(`Welcome, ${displayUser}`); // Output: "Welcome, Guest"
// Logical NOT (!)
let isActive = false;
console.log(`Is Active: ${!isActive}`); // Output: "Is Active: true"
// Nullish Coalescing (??)
let userSetting = null;
const finalSetting = userSetting ?? 'default_value';
console.log(`Final setting: ${finalSetting}`); // Output: "Final
setting: default_value"
const count = 0;
const displayCount = count ?? 'N/A';
console.log(`Display count: ${displayCount}`); // Output: "Display
count: 0" (because 0 is not null/undefined)
Short-Circuiting: Both && and || operators exhibit "short-circuiting" behavior. &&
evaluates from left to right and returns the first falsy value or the last operand if
all are truthy. || evaluates from left to right and returns the first truthy value or
the last operand if all are falsy. This makes them useful for conditional
execution and default assignments.
3. Comparison Operators
Comparison operators are used to compare two values and return a boolean result
(true or false). They are fundamental for decision-making in programs.
Operator Description ExampleResult
== Loose Equality: Checks for equality after type coercion. 5 == "5" true
Loose Inequality: Checks for inequality after type
!= 5 != "5" false
coercion.
Strict Equality: Checks for equality without type coercion
=== 5 === "5" false
(value AND type must be the same).
Strict Inequality: Checks for inequality without type
!== 5 !== "5" true
coercion.
> Greater than 10 > 5 true
< Less than 10 < 5 false
>= Greater than or equal to 10 >= 10 true
<= Less than or equal to 5 <= 10 true
Comparison Operators Example
JavaScript
let num1 = 10;
let strNum = "10";
let num2 = 5;
// Loose vs. Strict Equality
console.log(`num1 == strNum: ${num1 == strNum}`); // true (type
coercion)
console.log(`num1 === strNum: ${num1 === strNum}`); // false (no type
coercion)
console.log(`null == undefined: ${null == undefined}`); // true
console.log(`null === undefined: ${null === undefined}`); // false
// Relational Operators
console.log(`num1 > num2: ${num1 > num2}`); // true
console.log(`num1 <= num2: ${num1 <= num2}`); // false
console.log(`"apple" < "banana": ${"apple" < "banana"}`); // true
(lexicographical comparison)
Always Prefer Strict Equality (=== and !==): Unless you have a specific reason to
leverage type coercion, using strict equality is a fundamental best practice in
JavaScript. It prevents unexpected behavior due to implicit type conversions
and makes your code more predictable and reliable.
Best Practices
Use === and !==: Make strict equality your default for comparisons to avoid
surprising type coercion issues.
Understand + Operator Behavior: Be mindful that + can perform both addition and
concatenation. If you intend arithmetic, ensure both operands are numbers,
potentially using explicit conversion (e.g., Number(str) + num).
Leverage Short-Circuiting for Default Values/Conditional Execution: Utilize || for
providing default values (e.g., let user = currentUser || "Guest";) and && for
executing code only if a condition is met (e.g., userLoggedIn && showDashboard();).
Consider Nullish Coalescing (??): When dealing with truly null or undefined values
and wanting to provide a fallback, ?? is safer than || because it treats 0 or empty
strings as valid values.
Operator Precedence: Be aware of operator precedence (the order in which
operators are evaluated). If unsure, use parentheses () to explicitly control the
evaluation order, which also improves readability.
Operator Precedence Example:
JavaScript
console.log(2 + 3 * 4); // 14 (multiplication before addition)
console.log((2 + 3) * 4); // 20 (parentheses override precedence)
Common Mistakes
Using == instead of ===: This is a very common pitfall that leads to unexpected
comparisons due to type coercion.
Misunderstanding + behavior: Expecting addition when concatenation occurs
(e.g., "1" + 1 yielding "11" instead of 2).
Incorrectly using || for nullish checks: Using || when 0 or '' are valid values and
should not be replaced by a default (where ?? would be appropriate).
Forgetting operator precedence: Leading to incorrect calculations or logical
evaluations.
Summary: JavaScript operators are the verbs of the language, allowing you to
perform actions on data. Mastering arithmetic, logical, and comparison
operators, along with understanding their nuances (like type coercion and
short-circuiting), is fundamental to writing effective and bug-free JavaScript.
Always prioritize clarity and predictability in your code.
For more educational content and insights -
Connect with Sumedh