Skip to main content

Command Palette

Search for a command to run...

Operators: Welcome to the JavaScript Cafe

Published
12 min read
Operators: Welcome to the JavaScript Cafe

Introduction

Imagine walking into a cafe called the "JavaScript Cafe". Just like any other typical cafe, this one too has several ingredients, chefs who decide what to do with these ingredients as per the customer's wishes, and finally they create some dish based on the requirements.

If you think about it, we basically take some data (ingredients), put them together using some operations (as decided by the chefs), and create a final dish (result).

Programming works in a similar fashion. In every programming language, including JavaScript, we have a foundational concept called operators. In this blog post, we are going to explore what operators are, how they help us build expressions and all the different types of operators, all with a fun analogy of a cafe, particularly the JavaScript Cafe!


Tokens: Building Blocks of any Language

Before we get into operators, let's briefly talk about tokens. Whenever we write any program, the compiler/interpreter behind that language breaks it all down into tokens. Tokens are the smallest meaningful units of code in any language. The JavaScript engine also breaks down the code into these bits and pieces called tokens.

Diagram showing how the JavaScript statement let x = 5; is broken into tokens: let (keyword), x (identifier), = (operator), 5 (literal), and ; (separator).

You can think of tokens like words in a sentence. Just like sentences are made of words, programs are made up of tokens.

JavaScript has the following types of tokens:

Keywords

These are reserved or pre-defined words that have a special meaning.

Examples include:

let
const
function
return
if
else
class
await

Identifiers

These are names that we programmers give to variables, functions, classes, or objects.

Examples include:

let username = "Sameer";

function add(a, b) {
    return a + b;
}
  • In the above example, username and add are identifiers.

Literals

These represent fixed values written directly in code.

Examples include:

42
"Hello"
true
null

Separators

These are symbols used to structure the code.

Examples include:

;
,
.
()
{}
[]
:

Comments

Comments are simply some annotations in our code, that are straight up ignored by the JavaScript engine. These are useful for documentation.

Examples include:

// this is a single line comment

/*
this is a
multi-line
comment
*/

Operators

And finally, we have our operators. This blog post is specifically about operators in JavaScript. However, this brief section was important to help you understand that operators are simply some of many tokens that have a special meaning to the language.

Now what exactly are operators, why do we need them, etc. will all be covered in the rest of this blog post.


What are Operators?

Before getting into the types of operators, we need to understand what they even are, and why do we need them. The definition goes like:

Operators are symbols or keywords in programming that perform operations on variables and values (operands) to manipulate data.

However, such long and boring technical definitions do not enable us to understand and remember the concept easily. So let's take the example of our JavaScript Cafe. Let's say you walk into this beautiful Cafe, and order for a coffee. Based on your requirements, the chefs will gather all the ingredients and prepare a coffee for you.

Now this simple process involved the following parts:

  • Ingredients

  • Actions performed by the chefs on the ingredients

  • Your coffee

Similarly, in the context of programming, we have some input data (ingredients), and we want to get the output i.e. the final result (the coffee). In order to do that, it is required to perform certain actions on that input data (actions performed by the chefs).

Operators are the symbols that help us perform these actions. They are simply that glue, that help us put together some data, and generate some result. The simplest example would be:

5 + 2

Here, + is an operator, whose job is to sum up the numbers given to it.


Expressions

Now that we have a basic idea about operators, we need to understand one more term, which is pretty common in programming languages. An expression is simply a valid unit of code that evaluates to a single value. This value can be a number, a string, a boolean value, a function, etc.

In our analogy, we can think of an expression like an "order". In order to complete an order, we use several ingredients, instructions given by the customer, etc., and in the end we put it all together, to create a final dish.

Example:

5 + 2

This is a very simple expression. It produces the value 7.

Here,

  • 5 & 2 are the operands

  • + is the operator (just like we saw in the last section)

  • 7 is the output produced

Structure of expressions

Such expressions are built using operators. And we can use any valid combination of operators, to create any type of expression, no matter how simple or complex. A simple structure is given below:

Diagram illustrating operators and operands using the expression 5 + 2 * 6, where + and * are operators and 5, 2, and 6 are operands.

Types of Operators in JavaScript

Now that we understand what operators and expressions are, let's deep dive into the types of operators in JavaScript. Some of these concepts, even extend to other programming languages, since operators is a fundamental concept.

Following are the most commonly used types of operators in JavaScript:

  1. Arithmetic Operators

  2. Comparison/Relational Operators

  3. Logical Operators

  4. Assignment Operators

  5. Conditional/Ternary Operator


Arithmetic Operators

Arithmetic operators allow us to perform certain mathematical operations on data. Whenever we want to add, subtract, divide, multiply, etc. any values or variables, we make use of such arithmetic operators.

Think of them as how chefs add, remove, combine, etc. several ingredients to make dishes.

Operator Meaning Analogy
+ Addition Mix ingredients
- Subtraction Remove ingredients
* Multiplication Add an ingredient multiple times
/ Division Split portions
% Modulus Find leftovers
** Exponentiation Multiply an ingredient multiple times
++ Increment Add one extra ingredient
-- Decrement Remove one ingredient

Example Code

console.log(12 + 8);    // 20
console.log(15 - 6);    // 9
console.log(4 * 5);     // 20
console.log(20 / 4);    // 5
console.log(14 % 4);    // 2
console.log(3 ** 4);    // 81

let count = 10;
count++;
console.log(count);     // 11

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

Comparison/Relational Operators

If arithmetic operators are like preparing ingredients, then comparison operators are like checking ingredients before cooking.

Comparison operators, often referred to as Relational operators, allow us to compare data in our program. These always return a boolean value (true or false). These are very useful when writing conditional statements.

Operator Meaning Analogy
== Equal to Check if two ingredients look the same
=== Strict equal to Check if two ingredients are exactly the same
!= Not equal to Check if two ingredients are different
!== Strict not equal to Check if two ingredients are completely different
> Greater than Check which ingredient quantity is larger
< Less than Check which ingredient quantity is smaller
>= Greater than or equal to Check if an ingredient quantity is at least a certain amount
<= Less than or equal to Check if an ingredient quantity is at most a certain amount

Example Code

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

console.log(8 == "8");  // true
console.log(8 === "8"); // false

console.log(5 != 3);    // true
console.log(5 !== "5"); // true

Important: == and === are not the same

JavaScript has two operators for checking equality, and understanding their difference is extremely important.

The == operator checks if two values are equal, while ignoring their data types. In other words, it only cares about values, not the data types.

console.log(5 == 5);        // true     ->     this makes sense
console.log(5 == "5");      // true     ->     weird

If you've ever studied any other language, the above example might look weird. But the simple reason is, the == operator does not care about the data types.

On the other hand, the === operator does. It is called strict equality, and it checks both, values, as well as the data types.

console.log(5 === "5")    // false    ->    now it makes sense

Think of == as a casual comparison, and === as a strict comparison.

Recommendation

In most cases, prefer using === instead of ==. It avoids unexpected type conversions, and makes code more predictable in general.


Logical Operators

Logical operators represent decisions the chef makes before cooking.

Operator Meaning Analogy
&& Logical AND Cook the dish only if all ingredients are available
|| Logical OR Cook the dish if atleast one ingredient is available
! Logical NOT Check if an ingredient is not available

Just like Comparison operators, Logical operators also return boolean values. They help us combine multiple conditions together.

Example Code

let hasFlour = true;
let hasSugar = false;

console.log(hasFlour && hasSugar);  // false
console.log(hasFlour || hasSugar);  // true
console.log(!hasFlour);             // false

Truth Tables

Truth Tables simply allow us to look at all the possible outputs that a logical operator can produce based on the inputs.

Truth Table for Logical AND

Input A Input B A && B
true true true
true false false
false true false
false false false

It evaluates to true, only if both inputs are true. In all the other cases, it evaluates to false.

Truth Table for Logical OR

Input A Input B A || B
true true true
true false true
false true true
false false false

It evaluates to false, only if both inputs are false. In all the other cases, it evaluates to true.

Truth Table for Logical NOT

Input A !A
true false
false true

It simply flips the value. true becomes false, and false becomes true.


Assignment Operators

Assignment operators are simply used to store values in variables and update them later. In assignment operators, we have the simple = assignment operator, that assigns the value on the right-hand side, to the variable on the left-hand side.

However in addition to this, we also have several compound assignment operators. These include +=, -=, *=, etc. These are just shorthands for longer assignment statements. In other words, a += 5 is the same as a = a + 5.

As per our analogy, think of assignment operators like writing ingredients on a recipe board and modifying them as you cook.

Operator Meaning Analogy
= Assignment Write an ingredient on the recipe board
+= Add and assign Add more of an ingredient to the recipe
-= Subtract and assign Remove some quantity of an ingredient
*= Multiply and assign Increase the recipe quantity multiple times
/= Divide and assign Split the ingredient quantity
%= Modulus and assign Store the leftover quantity
**= Exponentiation and assign Multiply the ingredient by itself multiple times

Example Code

let quantity = 4;
console.log(quantity);      // 4

quantity += 3;
console.log(quantity);      // 7

quantity -= 2;
console.log(quantity);      // 5

quantity *= 2;
console.log(quantity);      // 10

quantity /= 5;
console.log(quantity);      // 2

quantity %= 2;
console.log(quantity);      // 0

quantity = 3;
quantity **= 2;
console.log(quantity);      // 9

Conditional/Ternary Operator

The conditional (ternary) operator is a shorter way to write simple if...else conditions. It chooses between two values based on whether a condition is true or false.

condition ? valueIfTrue : valueIfFalse

As per our analogy, you can think of it as choosing between two dishes based on available ingredients. If chocolate is available, make a chocolate cake, otherwise make a vanilla cake.

Example Code

let age = 18;

let message = age >= 18 ? "You can enter" : "Entry not allowed";

console.log(message);   // You can enter

Conclusion

JavaScript operators are the building blocks that allow us to perform calculations, compare values and make decisions in our programs. We looked at some of the most popular operators in this article, such as the conditional operator, arithmetic, comparison, logical, and assignment.

You will eventually feel more at ease utilizing operators in real-world code if you continue experimenting with small examples and try combining various operators.