DEV Community

Cover image for Beginner's Guide to JavaScript Operators - Part Two
Sumudu Siriwardana
Sumudu Siriwardana

Posted on • Updated on

Beginner's Guide to JavaScript Operators - Part Two

This article was originally published on Dasha.

In case you are wondering, Dasha is a conversational-AI-as-a-service platform that lets you embed realistic voice and text conversational capabilities into your apps or products. Start building for free!


Welcome to the second part of the Beginner's Guide to JavaScript Operator! 😊

To refresh your memory, In the first article, we have gone through the arithmetic and assignment operators, and operator precedence.

So let's see what we will be going over in this article.

Table of Contents

lets-get-going.gif

Comparison Operators

We use comparison operators to compare two values or variables. It is a binary operator which compares the operands and returns whether it's true or false depending on the comparison.

For example, if you want to check whether 10 is greater than 8, we use the greater than operator (>) and write it as, 10 > 8, then it returns true because 10 is greater than 8.

So, here's a list of comparison operators in JavaScript:

Operator Name Symbol Description Example
let x = 5
Equal == Returns true if the operands are equal x == '5'
(returns true)
Not equal != Returns true if the operands are not equal x != '6'
(returns true)
Strict equal === Returns true if the operands are equal and of the same type x === 5
(returns true)
Strict not equal !== Returns true if the operands are the same type but are not equal or are different types x !== '5'
(returns true)
Greater than > Returns true if the left operand is greater than the right operand x > 4
(returns true)
Greater than or equal >= Retruns true if left operand is greater than or equal to the right operand x > 5
(returns true)
Less than < Returns true if the left operand is less than the right operand x < 8
(returns true)
Less than or equal <= Returns true if the left operand is less than or equal to the right operand x <= 8
(returns true)

For equal comparison, we use the equal operator (==) and the strict equal operator (===). Why do we need two different operators for equal comparison? Let's find out.

There are different data types in JavaScript. When comparing two values of different types, JavaScript tries to convert these different data types into one data type. We call this type coercion. For example, let's say you have to compare a string with a number; JavaScript will try to convert the string into a number or the number into a string so that the values can be compared.

You can try the below code and see for yourself.

//Addition
let a = '11';
let b = 1;
console.log(a + b);  // '111'

//Subtraction
let a = '11';
let b = 1;
console.log(a - b);  // 10
Enter fullscreen mode Exit fullscreen mode

In the above example, when a and b are added together, JavaScript thinks it is string concatenation and converts the value of the b into a string, and concatenate a. So the output becomes a string, '111'.

But, when subtracting, JavaScript thinks it's an arithmetic operation so it converts everything into numbers and outputs the value as number 10.

Yeah, it's pretty strange! 😂

type-con.jpg

This topic requires a dedicated post itself. But let's try to get a basic idea of type coercion to understand the difference between equal and strict equal comparison.

Here is how the equal operator (==) compares operands:

  • First, it converts the value of the operands to a common type,
  • Then checks for the equality between them,
  • Then compares them and returns the boolean value.

While it looks like the equal operator doesn't consider the data type when comparing the two values. JavaScript actually first converts the values to the same data type implicitly and then compares the operands. Check the below example to understand this behavior.

let c = 10;

console.log(c == '10');   //true
console.log(c == 10);    //true

Enter fullscreen mode Exit fullscreen mode

The strict equal operator (===) compares both values and value types. It returns true only if both values and data types match with the other operand. Check the below example to understand this behavior.

let c = 10;

console.log(c === '10');   //false
console.log(c === 10);    //true

Enter fullscreen mode Exit fullscreen mode

Now you understand how equal comparison works. This same logic applies to not equal and strict not equal comparisons.

Let's move on to logical operators.

Logical Operators

We use logical operators to decide the logic between two variables or values. So it evaluates them and checks whether multiple conditions are true or false, then returns a boolean value.

First, let's see what are the logical operators and then understand how this basic boolean logic works.

Operator Name Symbol Description Example
Logical AND && Returns true if both the operands are true, else returns false true && true
(returns true),
true && false
(returns false)
Logical OR | | Returns true if either of the operands is true; returns false if both are false true | | false
(returns true),
false | | false
(returns false)
Logical NOT ! Returns true if the operand is false and vice-versa. !true
(returns false) !false
(returns true)

Here's see how this boolean logic actually works.

Check the below picture:

boolean-logic.png

In the above picture, we have two boolean variables that can be either true or false.

  • A: Sarah loves coffee
  • B: Coffee cup is empty

Now using the boolean operator, we can combine these two variables and use them to make a decision. For example, if Sarah loves coffee and the coffee cup is empty, then we can fill Sarah's coffee cup ☕️

We can use the truth table in the above picture to quickly calculate the result of the AND and OR operators.

So if we are using the AND (&&) logical operator, if all the operands are true, the result would be true. Else, even if one operand is false, then the result would be false. Check the below example:

const sarahLovesCoffee = true;  // A
const coffeeCupIsEmpty = false  // B

console.log(sarahLovesCoffee && coffeeCupIsEmpty);  // false
Enter fullscreen mode Exit fullscreen mode

When using the OR (||) logical operator, the result would be true even if one operand is true, even though the other operands are false. But, if all the operands are false, then the result would be false. Check the below example.

//At least one operand is true
const sarahLovesCoffee = true;  // A
const coffeeCupIsEmpty = false  // B

console.log(sarahLovesCoffee || coffeeCupIsEmpty);  // true

//Both operands are false
const sarahLovesCoffee = false;  // A
const coffeeCupIsEmpty = false  // B

console.log(sarahLovesCoffee || coffeeCupIsEmpty);  // false
Enter fullscreen mode Exit fullscreen mode

When it comes to the logical NOT (!) operator, it inverts the boolean result of the operand (or condition). Check the below example to understand this better.

const sarahLovesCoffee = true;  // A
const coffeeCupIsEmpty = false  // B

console.log(!sarahLovesCoffee);  // false
console.log(!coffeeCupIsEmpty);  // true
Enter fullscreen mode Exit fullscreen mode

Here's Drake's version of the logic gates 😂

drake-boolean.png

I hope that now you understand the basics of logical operators. So let's move on to ternary operators.

Ternary Operators

The ternary operator or the conditional operator allows us to write something similar to an if-else statement, but all in one line. It uses three operands and evaluates if a condition is true or false, and then returns one of the two values.

Below is the syntax for the ternary operator:

condition ? expressionIfTrue : expressionIfFalse
Enter fullscreen mode Exit fullscreen mode

So, according to the above syntax, If the condition is true, the first expression will be executed. Otherwise, the second expression will be executed.

Let's say that you want to check the age before deciding whether you are eligible to drive or not. You can simply write it as below:

age >= 18 ? "can drive" : "can't drive";
Enter fullscreen mode Exit fullscreen mode

So if the age 18 or above, then the first expression "can drive" is executed. Else the second expression "can't drive" is executed.

Now, remember that an operator always produces a value. In other words, an operator is an expression. So if we have a value, we can assign that value to a variable. Because of that, we can make a ternary operator useful to assign a value to a variable conditionally. So we can store the above expression in a variable.

Check the below example.

const age = 24;
const eligibleToDrive = age >= 18 ? "can drive" : "can't drive";
console.log(eligibleToDrive);   // "can drive"
Enter fullscreen mode Exit fullscreen mode

Let's see what we have done here;

  • We have declared a variable called age and given the value of 24.
  • Then, we have declared a variable to check the eligibility to drive - eligibleToDrive.
  • Then, we have assigned the ternary operator as the value for the eligibleToDrive variable. In this ternary operator we have given the condition as age >= 18, the first value as "can drive" (which will be executed if the condition is true), and the second value as "can't drive" (which will be executed if the condition is false).
  • When we console log the variable, eligibleToDrive, it prints the first expression from the ternary operator because the age is greater than 18.

Since the ternary operator is just a single line of code, it's often used as a shortened version of a simple if-else statement.

So that's about the ternary operator!

typeof Operator

The typeof operator can tell us about which data type a variable contains. Whether the value is a string, number, boolean, etc. It returns a string indicating the data type.

Now let's print a few values to see their types.

console.log(typeof true);             // 'boolean'
console.log(typeof false);            // 'boolean'
console.log(typeof 'Peter');          // 'string'
console.log(typeof 300);              // 'number'
console.log(typeof NaN);              // 'number'
console.log(typeof Infinity);         // 'number'
console.log(typeof [1, 2, 'John']);   // 'object'
Enter fullscreen mode Exit fullscreen mode

As you can see in the above example, with the typeof operator, we can check the data type of each value.


Okay, we made it to the end! 😂

This is all about the basics of JavaScript operators. Of course, there are more to these operators and more operators out there, but you can easily get through them when you understand these basics.

Thank you for reading this very long beginner's guide to the end!

Happy coding! 🤗

thank-you.gif


Visit Dasha AI
Join Dasha Developer Community where you’ll meet welcoming like-minded developers who share ideas, questions, and get all the help they need to build cool conversational AI apps (for free, of course).

Top comments (0)