DEV Community

Cover image for JavaScript Operators: The Basics You Need to Know
Janmejai Singh
Janmejai Singh

Posted on • Originally published at dev.to

JavaScript Operators: The Basics You Need to Know

Every JavaScript program β€” no matter how simple or complex β€” runs on operators. That + sign when you add two numbers? An operator. The === inside your if statement? Also an operator. The && that checks two conditions at once? Yep, operator.

They're everywhere, and once you truly understand them, reading and writing JavaScript becomes dramatically easier.

In this article, we'll cover the four essential operator categories that show up in everyday JavaScript code β€” with tables, console examples, and a practice assignment at the end.

Let's get into it. πŸš€


πŸ“‹ What We'll Cover


What Are Operators?

An operator is a symbol (or keyword) that performs an operation on one or more values. The values it operates on are called operands.

console.log(10 + 5); // 15
//           ↑   ↑
//      operand  operand
//             ↑
//          operator
Enter fullscreen mode Exit fullscreen mode

Simple enough. Now let's look at the four categories you'll use constantly.


Arithmetic Operators β€” Doing the Math

Arithmetic operators perform mathematical calculations. If you've done any basic math, these will feel instantly familiar.

Operator Name Example Output
+ Addition 10 + 3 13
- Subtraction 10 - 3 7
* Multiplication 10 * 3 30
/ Division 10 / 3 3.333...
% Modulus 10 % 3 1

Let's see them in action

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
Enter fullscreen mode Exit fullscreen mode

The Modulus Operator % β€” Don't Skip This One

The % operator trips up almost every beginner. It does not divide β€” it returns the remainder after division.

10 % 3 = 1 because 10 Γ· 3 = 3 remainder 1.

Its most practical use? Checking if a number is even or odd:

// Even numbers have no remainder when divided by 2
console.log(8 % 2 === 0); // true  β†’ even
console.log(7 % 2 === 0); // false β†’ odd
console.log(0 % 2 === 0); // true  β†’ even
Enter fullscreen mode Exit fullscreen mode

You'll see this pattern constantly in real JavaScript code.

πŸ’‘ Bonus: The + operator doubles as string concatenation. "Hello" + " World" produces "Hello World". Be mindful when mixing strings and numbers β€” JavaScript's automatic type conversion can produce unexpected results.


Comparison Operators β€” Asking True or False

Comparison operators compare two values and always return a boolean: either true or false. They're the foundation of every conditional statement you'll ever write.

Operator Name Example Output
== Loose equality "5" == 5 true
=== Strict equality "5" === 5 false
!= Loose inequality "5" != 5 false
> Greater than 10 > 3 true
< Less than 10 < 3 false

Basic comparisons

let x = 10;
let y = 20;

console.log(x > y);  // false β†’ 10 is not greater than 20
console.log(x < y);  // true  β†’ 10 is less than 20
console.log(x != y); // true  β†’ 10 is not equal to 20
Enter fullscreen mode Exit fullscreen mode

== vs === β€” The Difference Every JavaScript Developer Must Know

This is the most important distinction for any JavaScript beginner. Let's break it down clearly.

== (double equals) β€” Loose Equality
Converts types before comparing. JavaScript tries to make the two sides "match" before checking if they're equal. This is called type coercion.

=== (triple equals) β€” Strict Equality
Checks both the value and the type. No conversion happens. What you see is what gets compared.

// == performs type coercion (converts before comparing)
console.log("5" ==  5);          // true  ← "5" is converted to number 5
console.log(0   ==  false);      // true  ← 0 is treated as falsy
console.log(""  ==  false);      // true  ← empty string is falsy
console.log(null == undefined);  // true  ← special case

// === checks value AND type β€” no surprises
console.log("5" === 5);          // false ← string is not a number
console.log(5   === 5);          // true  ← same value, same type βœ…
console.log(0   === false);      // false ← number is not a boolean
console.log(null === undefined); // false ← different types
Enter fullscreen mode Exit fullscreen mode

Why does this matter in real projects?

HTML form inputs always return strings β€” even if the user types a number. Watch what happens:

// Simulating a value coming from a form input
let userAge = "18"; // this is a STRING, not a number

// == misleadingly says "yes, they match"
if (userAge == 18) {
  console.log("Access granted (==)"); // This runs β€” potentially a bug!
}

// === correctly catches the type mismatch
if (userAge === 18) {
  console.log("Access granted (===)"); // This does NOT run
} else {
  console.log("Type mismatch! Convert the input first."); // This runs βœ…
}
Enter fullscreen mode Exit fullscreen mode

⚠️ Golden rule: Always use === in your code. It prevents an entire class of subtle bugs caused by unexpected type coercion. Only reach for == if you have a very deliberate, specific reason β€” which is rare.


Logical Operators β€” Combining Conditions

Logical operators let you combine multiple conditions or invert a condition. They work with boolean values and are essential for writing meaningful if statements.

Operator Name Meaning Example
&& AND Both sides must be true age >= 18 && hasID
`\ \ ` OR
! NOT Inverts the boolean !isBanned

Truth Table β€” Every Possible Combination

Memorise this table. It defines how logical operators behave for every possible input:

| A | B | A && B | A \|\| B | !A |
|:---:|:---:|:---:|:---:|:---:|
| true | true | βœ… true | βœ… true | ❌ false |
| true | false | ❌ false | βœ… true | ❌ false |
| false | true | ❌ false | βœ… true | βœ… true |
| false | false | ❌ false | ❌ false | βœ… true |

The patterns to remember:

  • && β†’ only true when both are true. One false kills it.
  • || β†’ only false when both are false. One true saves it.
  • ! β†’ simply flips whatever you give it.

Code Examples

let age      = 22;
let hasID    = true;
let isBanned = false;
let isAdmin  = false;

// && (AND) β€” every condition must pass
console.log(age >= 18 && hasID);    // true  ← both are true
console.log(age >= 18 && isBanned); // false ← isBanned is false

// || (OR) β€” only one needs to pass
console.log(isAdmin || hasID);      // true  ← hasID is true
console.log(isAdmin || isBanned);   // false ← both are false

// ! (NOT) β€” flips the boolean
console.log(!isBanned); // true  ← not banned
console.log(!hasID);    // false ← has no ID
console.log(!isAdmin);  // true  ← not an admin
Enter fullscreen mode Exit fullscreen mode

Real-World Example β€” Access Control

let isLoggedIn       = true;
let isBanned         = false;
let hasVerifiedEmail = true;

// Can the user post a comment?
if (isLoggedIn && !isBanned && hasVerifiedEmail) {
  console.log("βœ… You can post a comment!");
} else {
  console.log("❌ Access restricted.");
}
// Output: "βœ… You can post a comment!"

// Can the user see the admin panel?
let isAdmin     = false;
let isModerator = true;

if (isAdmin || isModerator) {
  console.log("πŸ”‘ Welcome to the dashboard.");
}
// Output: "πŸ”‘ Welcome to the dashboard."
Enter fullscreen mode Exit fullscreen mode

πŸ’‘ Short-circuit evaluation: With &&, if the first condition is false, JavaScript skips evaluating the rest β€” it already knows the result is false. With ||, if the first condition is true, it stops immediately. This is called short-circuiting and is a common pattern in professional JavaScript.


Assignment Operators β€” Storing Values

Assignment operators store a value into a variable. The basic = sets a value, while compound operators combine a math operation and assignment into a single, shorter expression.

Operator Name Long form Short form Result
= Assign x = 10 β€” x is 10
+= Add & assign x = x + 5 x += 5 x is 15
-= Subtract & assign x = x - 3 x -= 3 x is 12

Code Examples

let score = 0;
console.log(score); // 0

// += adds to the current value and saves it back
score += 10;
console.log(score); // 10

score += 5; // player earns a bonus
console.log(score); // 15

score -= 3; // player takes damage
console.log(score); // 12
Enter fullscreen mode Exit fullscreen mode

Works with strings too

let greeting = "Hello";
greeting += ", ";
greeting += "World!";
console.log(greeting); // "Hello, World!"
Enter fullscreen mode Exit fullscreen mode

All four operator types working together

let itemPrice    = 200;
let discountRate = 20;
let taxPercent   = 10;
let isPremium    = true;
let hasCoupon    = false;

// Arithmetic + Assignment
itemPrice -= discountRate;                    // 180 after discount
let tax   = itemPrice * (taxPercent / 100);   // 18
let total = itemPrice + tax;                  // 198

// Comparison + Logical
if (total > 100 && (isPremium || hasCoupon)) {
  console.log("🚚 Free shipping applied!");
}

console.log("Order total: $" + total);
// Output: "🚚 Free shipping applied!"
// Output: "Order total: $198"
Enter fullscreen mode Exit fullscreen mode

🎯 Hands-On Practice Assignment

The best way to learn operators is to write them yourself. Try each task below before peeking at the solutions.


Task 1 β€” Arithmetic on two numbers

// Declare two variables
let num1 = 25;
let num2 = 7;

// Your job: perform and log all 5 arithmetic operations
// Expected outputs: 32, 18, 175, 3.571..., 4
Enter fullscreen mode Exit fullscreen mode

Task 2 β€” Compare values with == and ===

let valueA = "25"; // string
let valueB = 25;   // number

// Your job: compare valueA and valueB using both == and ===
// Log both results and observe the difference
Enter fullscreen mode Exit fullscreen mode

Task 3 β€” Write a condition using logical operators

let isLoggedIn       = true;
let isBanned         = false;
let hasVerifiedEmail = true;

// Your job: write an if/else that logs:
// "You can post!" if the user is logged in, not banned, and email-verified
// "Access denied." otherwise
Enter fullscreen mode Exit fullscreen mode

Click to reveal solutions

Solution β€” Task 1

let num1 = 25;
let num2 = 7;

console.log(num1 + num2); // 32
console.log(num1 - num2); // 18
console.log(num1 * num2); // 175
console.log(num1 / num2); // 3.5714285714285716
console.log(num1 % num2); // 4  ← 25 Γ· 7 = 3 remainder 4
Enter fullscreen mode Exit fullscreen mode

Solution β€” Task 2

let valueA = "25";
let valueB = 25;

console.log(valueA ==  valueB); // true  ← type coercion kicks in
console.log(valueA === valueB); // false ← string !== number

// Takeaway: === is safer. It tells you the types don't match.
Enter fullscreen mode Exit fullscreen mode

Solution β€” Task 3

let isLoggedIn       = true;
let isBanned         = false;
let hasVerifiedEmail = true;

if (isLoggedIn && !isBanned && hasVerifiedEmail) {
  console.log("You can post! βœ…");
} else {
  console.log("Access denied. ❌");
}
// Output: "You can post! βœ…"
Enter fullscreen mode Exit fullscreen mode


πŸ“Œ Quick-Reference Summary

Category Operators Key Takeaway
Arithmetic + - * / % % returns the remainder, not the quotient
Comparison == === != > < Always prefer === β€” it checks type too
Logical && `\ \
Assignment {% raw %}= += -= Shortcuts that update and reassign in one step

What to Learn Next

Now that operators feel solid, here's a natural path forward:

  1. Conditional statements (if, else if, switch) β€” using comparison and logical operators to control flow
  2. Loops (for, while) β€” where <, ++, and += become your best friends
  3. Functions β€” wrapping your operator logic into reusable, named blocks
  4. Arrays and objects β€” where you'll apply everything you've learned here at scale

Final Thoughts

Operators might seem like a tiny topic, but they're the core of how JavaScript thinks. Every condition you check, every value you update, every calculation you run β€” it all comes back to operators.

Take the time to really absorb == vs ===. Spend 10 minutes playing with the modulus %. Write out that truth table from memory. These small investments pay off every single day as a developer.

Drop your Task 3 solution in the comments β€” I'd love to see how you approached it! πŸ‘‡

Top comments (0)