Skip to main content

Command Palette

Search for a command to run...

JavaScript Operators: The basics you need to know.

Published
10 min read
JavaScript Operators: The basics you need to know.

Operators

Operators are the way to perform mathematical operations in any programming language, and yes, JavaScript also has many of them.

Generally, there are at most 3 types of operators

  1. Arithmetical operators

  2. Logical Operators

  3. Relational Operators

You will find many others as well, but most will be in one of the types above.

Arithmetical Operators

These are the operators that perform mathematical operations such as addition and subtraction.

% is not percentage in programming. It is called modulus (returns the remainder).

Some operators:

  1. [ + ] Addition

  2. [ - ] Subtraction

  3. [ * ] Multiplication

  4. [ / ] Multiplication

  5. [ % ] Modulus

All the above operators you would have used in your life, right, so I'm just explaining about the modulus (%) operator

In the above image, as you can see, I have done a simple division, which we learn in our schools.

So the answer is 25 / 2 = 12.5 right, which we also called Quotient in Division. But in modulus, we divide the number until we get the remainder (Integer Quotient, not decimal), and then the remainder, which we get, is the final result of modulus.

We use modulus in the same way we use division; just in case of modulus, we replace the division symbol (/) with the modulus symbol (%).

Now we also have Unary Operator, which comes under the Arithmetic Operators. Unary Operator means the operator which perform action with just a sinlge operands.

In programming operands means a variable, constant , value or expression on which operations can be performed by operators.

Like In:

const cirecleArea = 2 * Math.pi * r ^ 2;

const squareArea = ( length + breadth ) * 2

In above code 2, Math.pi, length, breadth are the operand in which operations are performed by operators.

Unary Operators have 2 things with them

  1. The symbols, which are the Increment Operator ( ++ ) and the Decrement Operator ( -- )

  2. Position of these Operators: Prefix (Before the operand) and Postfix (After the operand)

First, lets undertstand the concept of positions.

When we write something like ++a In our code, it represents a prefix increment operator because the Increment (++) operator is used before the operand (a). Similarly, when we write like a++ In our code, it represents a postfix increment operator because the Increment (++) operator is used after the operand (a).

Ok, now you would have understood the meaning of postfix and prefix in unary operators. Now let's understand what does this (++) and (--) symbols do and how the final values are evaluated.

The final evaluation is not just depended on the unary operator but also on the position it is used. Also always keep in mind that ++ or -- operators only increase or decrease the value with 1 only not less that that nor more than that. But when it will increase or decrease will depends on the position it is beign used.

Below is the simple code given. Run that in your browser or in your Node environment. Then continue reading the blog to understand the real meaning of it.

let a = 10;
console.log(++a);
console.log(++a);
console.log(a);
console.log(a++);
console.log(a++);
console.log(a);

let b = 10;
console.log(--b);
console.log(--b);
console.log(b);
console.log(b--);
console.log(b--);
console.log(b);

Whenever we use the increment operator in the prefix position, it increments the value by 1 instantly of that operand. And when we use the increment operatorin the postfix position, it doesn't increment the value at the very instant, but whenever we use it in the future, then it will add 1 to that operand.

I know, I know, the last line is a little confusing, but bear with me, read the last sentence 2-3 times, and continue reading.

let a = 10;
// As we are using increment operator in prefix position, it will update the value of a from 10 -> 11 instantly
console.log(++a); // output: ++a = a + 1 = 10 + 1 = 11

// Now as the value of 'a' is updated to 11, from here onward the value of 'a' will be 11 until an unless we update it to something else.
// And now this time as we are using the increment operator but this time in postfix position, it will not update the value at the instant. Instead it will forward that if 'a' is used in the future or not, if yes, it will add on that place
console.log(a++); // output: a++ = a = 11
// From the previous line 'a++'
console.log(a);   // output: a = a + 1 = 11 + 1 = 12

Below is the visual representation of similar code.

This is how you can visualize the whole process of the unary operator. And in case of the decrement operator, you just have to decrease the value by one, like below.

Hopefully, you have understood the concept of Unary Operator, and to test that, there is a little task for you guys. Do let me know the answer in the comments.

// Q1. 
let a = 10, b = 20;
const finalValue = ++a + ++b - b-- - a-- + a++ - --b
console.log(finalValue);

// Q2.
for (var i = 10; i < 20; ++i) {
    console.log(i);
    i += 2 // i += 2 => i = i + 2 => i = 2 + 2 => i = 4;
}

// Q3.
for (var i = 10; --i > 0; i--) {
    console.log(i);
}

Question 1 is a little bit tricky, so I am providing the visual solution to that as well.

Relational Operators

The next set of operators we have in our bucket list is Relational Operator.

You would be familiar with this, as it is also taught in school; the operators are <, >, <=, >=, !=, ==

But, is javascript we also have === . Now you will ask what the difference is between double equal two and triple equal two. Nothing much, like double equal too is too strict, but triple equal to is very strict, like your maths teacher who cuts your whole marks even if the last line of your solution is wrong.

Whenever you use the double equal sign, JavaScript tries to convert the data into nearly all possible data types (implicit data type conversion) so that both the values can match. Just like your English teacher who sometimes forgives your grammar or spelling mistakes and gives you the full marks.

The Golden Rule Most Senior Engineers Follow

Use this mental rule:

Always use === and !==
unless you have a very specific reason not to.

This prevents JavaScript type coercion chaos.

Because things like this exist:

[] == false   // true
"" == 0       // true
"0" == false  // true

JavaScript code example for all the Relational Operators.

const age = 10 == "10";
const marks = 45 === "45";

console.log(age);   // Output: true
console.log(marks); // Output: false


const userAge = 18;

if (userAge === 18) {
  console.log("User is exactly 18");
}

const status = "inactive";

if (status !== "active") {
  console.log("User cannot access dashboard");
}

const score = 90;

if (score > 80) {
  console.log("Excellent performance");
}

const temperature = 10;

if (temperature < 15) {
  console.log("It's cold outside");
}

const age = 18;

if (age >= 18) {
  console.log("Allowed to vote");
}

const itemsInCart = 5;

if (itemsInCart <= 10) {
  console.log("Eligible for small package shipping");
}

// Real world senarios

function canAccessDashboard(user) {

  if (user === null) return false;

  if (user.role !== "admin") return false;

  if (user.loginAttempts >= 5) return false;

  return true;
}

Logical Operator

Let's move to logical operators.

So what exactly are logical operators?

They help us to make logical decisions, like whether we should do this or that.

We have 3 different operators under logical operators:

  1. And ( && )

  2. Or ( && )

  3. Not ( && )

Let's go inside the code and understand its working.

1. && (AND operator)

Think of && as a strict parent.

Everything must be correct.
If one condition fails, the whole plan is cancelled.

Real life example

You want to go out with friends.

But your mom says:

You can go out IF
you finish homework AND clean your room

So the rule becomes:

homeworkDone && roomClean

Code version:

const homeworkDone = true
const roomClean = false

if (homeworkDone && roomClean) {
  console.log("You can go outside")
} else {
  console.log("Stay at home and suffer")
}

Since the room is not clean:

true && false → false

Result:

Stay at home

The AND operator is basically saying:

“No shortcuts. Everything must be done.”

Example from real apps:

if (userLoggedIn && userRole === "admin") {
  console.log("Access granted")
}

Meaning:

User must be logged in
AND
User must be admin

Otherwise:

Security guard says: "Nice try."

2. || (OR operator)

This one behaves like a lazy friend. Only one condition needs to be true.

Real life example

You’re ordering food.

Your brain says:

If pizza OR burger is available, I will eat.

Expression:

pizzaAvailable || burgerAvailable

Code:

const pizzaAvailable = false
const burgerAvailable = true

if (pizzaAvailable || burgerAvailable) {
  console.log("Food secured. Happiness restored.")
}

Output:

Food secured. Happiness restored.

Even though pizza is unavailable, burger saves the day.

OR operator basically says:

“I’m not picky. Just give me something.”


3. ! (NOT operator)

This is the opposite machine.

It flips truth like a light switch.

Real-life example

Your brain is checking Monday morning motivation.

motivated = false

Then someone asks:

Are you NOT motivated?

Code:

const motivated = false

if (!motivated) {
  console.log("Back to sleep")
}

! flips the value:

!false → true

So the output is:

Back to sleep

NOT operator basically says:

“Whatever this was… do the opposite.”

Assignments

Guess the Output

const a = 10;
const b = "10";
const c = 20;

console.log(a == b);
console.log(a === b);
console.log(a != b);
console.log(c > a);
console.log(a < c);
console.log(a >= 10);
console.log(c <= 15);

Fix the Logic

const marks = "40";

if (marks == 40) {
    console.log("Student scored exactly 40");
}

if (marks >= 40) {
    console.log("Student passed");
}

if (marks < 40) {
    console.log("Student failed");
}

if (marks != 100) {
    console.log("Student did not get full marks");
}

More from this blog

B

Barun Tiwary

25 posts