Tutorials Logic, IN info@tutorialslogic.com
Navigation
Home About Us Contact Us Blogs FAQs
Tutorials
All Tutorials
Services
Academic Projects Resume Writing Website Development
Practice
Quiz Challenge Interview Questions Certification Practice
Tools
Online Compiler JSON Formatter Regex Tester CSS Unit Converter Color Picker
Compiler Tools

JavaScript Operators Arithmetic, Logical, Comparison: Tutorial, Examples, FAQs & Interview Tips

JavaScript Operators

Operators are symbols or keywords that perform operations on values. The values used with operators are called operands. For example, in 10 + 5, the + symbol is the operator, and 10 and 5 are operands.

JavaScript operators are used for arithmetic, assignment, comparison, logic, strings, objects, arrays, type checking, and more. Understanding them is essential before learning conditions, loops, functions, and DOM programming.

Arithmetic Operators

Arithmetic operators perform mathematical calculations on numbers. JavaScript also uses + for string concatenation, so the result depends on the operand types.

OperatorNameExampleResult
+Addition10 + 313
-Subtraction10 - 37
*Multiplication10 * 330
/Division10 / 33.333...
%Remainder10 % 31
**Exponentiation2 ** 38
++Incrementx++Adds 1
--Decrementx--Subtracts 1
Arithmetic Operators
let a = 10;
let b = 3;

console.log(a + b);  // 13
console.log(a - b);  // 7
console.log(a * b);  // 30
console.log(a / b);  // 3.3333333333333335
console.log(a % b);  // 1
console.log(a ** b); // 1000

let count = 5;
count++;
console.log(count); // 6

count--;
console.log(count); // 5

Prefix and Postfix Increment

The increment and decrement operators can be used before or after a variable. Prefix form updates first and then returns the new value. Postfix form returns the old value first and then updates.

Prefix vs Postfix
let x = 5;

console.log(++x); // 6: increase first, then use value
console.log(x);   // 6

let y = 5;

console.log(y++); // 5: use value first, then increase
console.log(y);   // 6

Assignment Operators

Assignment operators store values in variables. Compound assignment operators update a variable using its current value.

OperatorMeaningSame As
=Assignx = 10
+=Add and assignx = x + 5
-=Subtract and assignx = x - 5
*=Multiply and assignx = x * 5
/=Divide and assignx = x / 5
%=Remainder and assignx = x % 5
**=Power and assignx = x ** 2
Assignment Operators
let total = 10;

total += 5;  // 15
total -= 3;  // 12
total *= 2;  // 24
total /= 4;  // 6
total %= 4;  // 2
total **= 3; // 8

console.log(total);

Comparison Operators

Comparison operators compare two values and return a boolean result: true or false. They are commonly used in if statements, loops, filters, and validations.

OperatorNameExampleResult
==Loose equality5 == "5"true
===Strict equality5 === "5"false
!=Loose not equal5 != "5"false
!==Strict not equal5 !== "5"true
>Greater than10 > 5true
>=Greater than or equal10 >= 10true
<Less than3 < 5true
<=Less than or equal3 <= 2false
Strict vs Loose Equality
console.log(5 == "5");   // true: JavaScript converts the string to number
console.log(5 === "5");  // false: number and string are different types

console.log(false == 0);  // true
console.log(false === 0); // false

console.log(10 > 5);      // true
console.log(10 >= 10);    // true
console.log(3 < 2);       // false

Logical Operators

Logical operators combine or reverse boolean expressions. JavaScript also uses short-circuit evaluation, which means it may stop evaluating as soon as the final result is known.

OperatorNameReturns true when
&&Logical ANDBoth values are truthy
||Logical ORAt least one value is truthy
!Logical NOTReverses truthiness
Logical Operators and Short-Circuiting
const isLoggedIn = true;
const isAdmin = false;

console.log(isLoggedIn && isAdmin); // false
console.log(isLoggedIn || isAdmin); // true
console.log(!isLoggedIn);           // false

// Short-circuit example
isLoggedIn && console.log("Welcome back!");

const username = "";
const displayName = username || "Guest";
console.log(displayName); // Guest

Truthy and Falsy Values

Logical operators depend on truthiness. A value does not need to be exactly true or false; JavaScript can treat it as truthy or falsy in boolean contexts.

Falsy ValuesTruthy Values
falseNon-empty strings such as "hello"
0, -0, 0nNon-zero numbers such as 10
""Arrays, even empty arrays []
nullObjects, even empty objects {}
undefinedFunctions
NaNDates, maps, sets, and most created values

String Operators

The + operator joins strings when at least one operand is a string. This is called concatenation. Modern JavaScript often uses template literals because they are easier to read.

String Concatenation
const firstName = "Ada";
const lastName = "Lovelace";

console.log(firstName + " " + lastName); // Ada Lovelace

let message = "Hello";
message += ", JavaScript!";
console.log(message); // Hello, JavaScript!

const age = 28;
console.log("Age: " + age); // Age: 28
console.log(`Age: ${age}`); // Age: 28

Ternary Operator

The ternary operator is a short form of an if...else expression. It is useful when choosing between two values.

Ternary Operator
const age = 19;

const status = age >= 18 ? "Adult" : "Minor";
console.log(status); // Adult

const score = 72;
const result = score >= 40 ? "Pass" : "Fail";
console.log(result); // Pass

Nullish Coalescing Operator

The nullish coalescing operator ?? returns the right-side value only when the left-side value is null or undefined. It is safer than || when values like 0, false, or an empty string are valid.

Nullish Coalescing
const savedVolume = 0;

const volumeWithOr = savedVolume || 50;
console.log(volumeWithOr); // 50: not what we wanted

const volumeWithNullish = savedVolume ?? 50;
console.log(volumeWithNullish); // 0: correct

const username = null;
console.log(username ?? "Guest"); // Guest

Optional Chaining Operator

The optional chaining operator ?. safely accesses nested properties or methods. If the value before ?. is null or undefined, JavaScript returns undefined instead of throwing an error.

Optional Chaining
const user = {
    name: "Maya",
    profile: {
        email: "maya@example.com"
    }
};

console.log(user.profile?.email);   // maya@example.com
console.log(user.address?.city);    // undefined

const onSave = null;
onSave?.(); // no error

Logical Assignment Operators

Logical assignment operators combine logical checks with assignment. They are useful for setting defaults or updating values only under specific conditions.

OperatorAssigns whenExample
||=Current value is falsyx ||= 10
&&=Current value is truthyx &&= 10
??=Current value is null or undefinedx ??= 10
Logical Assignment
let title = "";
title ||= "Untitled";
console.log(title); // Untitled

let token = "abc123";
token &&= "hidden";
console.log(token); // hidden

let limit = 0;
limit ??= 10;
console.log(limit); // 0

Spread and Rest Operators

The ... syntax can be used as spread or rest depending on where it appears. Spread expands values. Rest collects values.

Spread and Rest
// Spread: expands an array
const numbers = [1, 2, 3];
const moreNumbers = [...numbers, 4, 5];
console.log(moreNumbers); // [1, 2, 3, 4, 5]

// Spread: copies object properties
const user = { name: "Asha", role: "student" };
const updatedUser = { ...user, active: true };
console.log(updatedUser);

// Rest: collects remaining function arguments
function sum(...values) {
    return values.reduce((total, value) => total + value, 0);
}

console.log(sum(10, 20, 30)); // 60

Destructuring Assignment

Destructuring is a special assignment syntax that extracts values from arrays or objects into variables.

Destructuring Assignment
const colors = ["red", "green", "blue"];
const [firstColor, secondColor] = colors;

console.log(firstColor);  // red
console.log(secondColor); // green

const product = {
    name: "Laptop",
    price: 65000
};

const { name, price } = product;
console.log(name);  // Laptop
console.log(price); // 65000

Type Operators

JavaScript provides operators for checking types and object relationships. The most common are typeof, instanceof, in, and delete.

OperatorPurposeExample
typeofReturns the type as a stringtypeof 42
instanceofChecks object prototype relationship[] instanceof Array
inChecks whether a property exists"name" in user
deleteDeletes an object propertydelete user.age
Type and Object Operators
console.log(typeof "hello"); // string
console.log(typeof 42);      // number
console.log(typeof null);    // object: historical JavaScript behavior

console.log([] instanceof Array); // true

const user = { name: "Riya", age: 22 };
console.log("name" in user); // true

delete user.age;
console.log(user); // { name: "Riya" }

Bitwise Operators

Bitwise operators work on 32-bit integer representations of numbers. They are less common in everyday web development but useful in flags, permissions, low-level algorithms, and performance-sensitive logic.

OperatorNameExample
&Bitwise AND5 & 1
|Bitwise OR5 | 1
^Bitwise XOR5 ^ 1
~Bitwise NOT~5
<<Left shift5 << 1
>>Signed right shift5 >> 1
>>>Unsigned right shift5 >>> 1

Operator Precedence

Operator precedence decides which operation runs first. Multiplication runs before addition, comparisons run before logical operators, and parentheses can be used to make the order clear.

Precedence Examples
console.log(2 + 3 * 4);     // 14
console.log((2 + 3) * 4);   // 20

const age = 20;
const hasId = true;

const canEnter = age >= 18 && hasId;
console.log(canEnter); // true

Complete Practice Example

This example combines arithmetic, comparison, logical, ternary, nullish coalescing, optional chaining, and assignment operators in a simple shopping cart calculation.

Shopping Cart Operators Example
const cart = {
    item: "Keyboard",
    price: 1200,
    quantity: 2,
    coupon: null,
    customer: {
        name: "Neha",
        isMember: true
    }
};

let subtotal = cart.price * cart.quantity;
const discount = cart.coupon ?? 0;

subtotal -= discount;

const deliveryCharge = subtotal >= 2000 ? 0 : 100;
const memberBonus = cart.customer?.isMember && subtotal > 1000;

const total = subtotal + deliveryCharge;

console.log(`Customer: ${cart.customer?.name ?? "Guest"}`);
console.log(`Item: ${cart.item}`);
console.log(`Subtotal: ${subtotal}`);
console.log(`Delivery: ${deliveryCharge}`);
console.log(`Member bonus: ${memberBonus}`);
console.log(`Total: ${total}`);

Common Mistakes

  • Using = instead of === inside a condition.
  • Using == when strict equality === is safer and clearer.
  • Using || for defaults when 0, false, or "" should be preserved.
  • Forgetting that + concatenates strings when one operand is a string.
  • Writing complex expressions without parentheses, making the code hard to read.
  • Confusing prefix increment ++x with postfix increment x++.

Frequently Asked Questions

Operators are symbols or keywords that perform operations on values, such as arithmetic, comparison, assignment, logical checks, and type checks.

== compares values after type conversion, while === compares both value and type. In most code, prefer ===.

|| falls back for any falsy value, including 0 and empty strings. ?? falls back only for null or undefined.

Optional chaining ?. safely accesses nested properties or methods and returns undefined if a parent value is null or undefined.

Use the ternary operator for simple two-choice expressions. For complex logic, an if...else block is easier to read.

Key Takeaways
  • Operators perform actions on operands, such as adding, comparing, assigning, or checking values.
  • Prefer strict equality === and strict inequality !== to avoid type coercion surprises.
  • Use ?? when only null or undefined should trigger a default value.
  • Use ?. to safely access nested properties without throwing errors.
  • Use parentheses to make complex operator precedence clear.
  • Remember that + can add numbers or concatenate strings depending on operand types.

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.