Skip to main content

Command Palette

Search for a command to run...

Js Operators

Updated
9 min read
Js Operators

Introduction

Hello readers...

In the previous blog, I covered variables in depth and gave an overview of data types. Thank you so much for the love you showed on my previous blog. If you haven't read it yet, check it out here: Variables & Data Types.

In this blog, I'm going to cover operators. When you hear "operators," it sounds very mathematical, right?

But operators are something we use every single day in our lives without realizing it.

Imagine this:

You go to a grocery store and buy

2 biscuits & 3 chocolates

Now you ask the shopkeeper: Kitna hua? (How much?)

The shopkeeper quickly calculates

(2*10) + (3*5) = 35

That + and * sign is doing the work. It combines the values and returns a result. And that is exactly what an operator does in a programming language.

What is an operator?

An operator is a symbol which perform some kind of operation on our values (operands).

Example:

let a = 5;
let b = 3;
let sum = a+b;
console.log(a+b);

Without Operators, JS has only data with no action.

Why do we need operators?

Imagine you are building an e-commerce application.

A customer buys:

  • shirt - 3000 INR

  • shoes - 20000 INR

Now you have to calculate the total to generate the bill.

Without operators, it is not possible.

That's why we need operators.

Operators allow us to:

  1. Calculate values

  2. Compare values

  3. Assign values

  4. Make decisions

💡
Operators bring logic and action to our code.

Types of Operators

Based on the number of operands, operators are divided into 3 parts.

  1. Binary operators (require 2 variables)

  2. Unary Operators (require only 1 variable)

  3. Ternary Operators ( require 3 variables)

Let's start with the binary operators.

  1. Binary Operators

Operators that have only two operands are known as binary operators. There are many binary operators that can be categorized into 5 types.

  • Arithmetic Operators

  • Assignment Operators

  • Comparison Operators

  • Logical Operators

  • Bitwise Operators

Let's learn each of these operators

Arithmetic operators are used to do mathematical operations like addition, subtraction, multiplication, and division. Here are those operators:

Operator Meaning Example
+ Addition 3+5 = 8
- Subtraction 5-3 = 2
* Multiplication 5*3 = 15
/ Division 10/2 = 5
** Exponential 3**3 = 27 (3X3X3)
% Modulus (gives you the remainder) 10%3 = 10

Here are some concepts you must know about the arithmetic operators:

  1. Operator precedence:

If there are multiple arithmetic operators in an expression, then operator precedence decides which one will first execute.

Precedence Operator Type Individual Operators Associativity
4 Grouping ( ) n/a
3 Exponentiation ** Right-to-Left
2 Multiplicative * / % Left-to-Right
1 Additive + - Left-to-Right
💡
If the same precedence operators are there, then according to the associativity value is calculated.
  1. "+" operator has multiple role

+ operator can be used to concatenate the words, so when you try to use it with a string, it will concatenate them by converting the number to a string.

Here are some other examples of + and - operators on different datatypes

  • Assignment Operators

Assignment Operators are used to assign values to a variable. for example:

let a = 5;

We can also compound the assignment operators with the arithmetic operators, and these compounded operators are known as arithmetic assignment operators.

Operator Meaning Example
+= Add to the original variable and assign the result a += 10;
-= subtract from the original variable and assign the result a -= 10
*= Multiply by the original variable and assign the result a *= 10
/= Divide the original value from the given value and assign the result a /= 2
  • Comparision Operators

Comparison operators are used to compare the values, like equal or not, greater or smaller, etc.

These operators give a result in Boolean.

Here are these operators:

Operator Meaning Example
== Compare by value 5 == "5"; (true)
=== Compare by value and data type (strict checking) 5 === "5"; (false)
> Check if the left side value is greater 5 > 3; (true)
< Check if the left side value is smaller 5 < 3 (false)
>= Returns true if the value is greater than or equal to 5>= 5 (true)
<= Returns true if the value is smaller than or equal to 5 <= 3 (true)
!= Returns true if the value is not equal 5 != 5 (false)
  • Logical Operators

A logical operator is used to determine the logic between the variable or values.

In JS, logical operators not just return true or false, they can return any data type and can work on any data type.

There are 4 logical operators in JS.

|| (OR)

  • Logical OR is represented by ||

  • It can be applied to any data type, and it can also return any data type.

  • It evaluate operands from left to right.

  • It searches for the first truthy value, and if found, then returns that value (no changes). If no truthy value exists, then it returns the last value (even if that is false)

&& (AND)

  • It is represented by && (double ampersand symbol).

  • It starts to find the first falsy value. If found, then return; otherwise, return the last value.

! (Logical not)

The Boolean NOT operator is represented with an exclamation sign !. Logical not is used to invert true to false and vice versa.

The operator accepts a single argument and does the following:

  1. Converts the operand to the Boolean type: true/false.

  2. Returns the inverse value.

A double NOT !! is sometimes used for converting a value to a Boolean type

Nullish coalescing (??) operator

  • Nullish ?? Returns the first argument if it’s not null/undefined. Otherwise, the second one.

  • The nullish coalescing operator isn’t anything completely new. It’s just a nice syntax to get the first “defined” value of the two.

  • The common use case for ?? is to provide a default value.

  • The difference between ?? and || is: ?? returns the first defined (neither null nor undefined), and || returns the first truthy value

let user;

console.log(user ?? "Anonymous"); // Anonymous (user is undefined)

//it can also be written as
let result = user ? user : "Anonymous" (This is ternary operator, will see in the blog)
console.log(result) //same result
💡
The precedence of AND && operator is higher than OR ||.
💡
The precedence of ! is higher than all logical operators.
  • Bitwise Operators

Bitwise operatos works on the bits, so it converts the number into bits and then does the operation.

Operator Name Description
& AND Sets each bit to 1 if both bits are 1
` ` OR
^ XOR Sets each bit to 1 if only one of two bits is 1
~ NOT Inverts all the bits
<< Zero fill left shift Shifts left by pushing zeros in from the right and let the leftmost bits fall off
>> Signed right shift Shifts right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off
>>> Zero fill right shift Shifts right by pushing zeros in from the left, and let the rightmost bits fall off

Example:

Operation Result Same as Result
5 & 1 1 0101 & 0001 0001
5 1 5 0101
~ 5 10 ~0101 1010
5 << 1 10 0101 << 1 1010
5 ^ 1 4 0101 ^ 0001 0100
5 >> 1 2 0101 >> 1 0010
5 >>> 1 2 0101 >>> 1 0010

Unary Operator

Unary Operators take a single operand and perform the operation. Here are those operators:

  1. Unary Plus (+) and Unary minus (-): It is used to negate the sign

  2. Increment(++) and Decrement (--):

It increments and decrements the value. It can be further divided into pre or post.

💡
logical not is also a unary operator.

Ternary Operator

The ternary operator takes 3 operands. It is a shorter form of if-else.

syntax:

condition ? value1 : value2

Here is if the condition is true, then return value1, otherwise value 2

let age = 30;
let message = age >= 18 ? "Adult" : "Minor";

console.log(message) //output: Adult

That’s it for this blog. I hope it helped you understand JavaScript operators more deeply — especially the logical operators.

If you found this helpful, feel free to share your feedback and consider sharing it with your friends who are learning JavaScript.

What’s Next?

In the next blog, we’ll dive into decision-making in programming using if-else and switch statements.

We’ll explore how programs make decisions and how these decisions can directly impact the behavior of your applications.

See you in the next one 🚀