NEW Try Zapier integration to connect Dasha instantly to thousands of the most popular apps!

JavaScript Operators: Beginner's Guide Part 2

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.

In this article we will be exploring the followings:

  • Comparison Operators
  • Logical Operators
  • Ternary Operators
  • typeof Operator
  • Void Operator
  • Instanceof Operator
  • Comma Operator
  • Delete Operator
  • Grouping Operator
  • Binary Bitwise Operators

Comparison Operators

We use JS 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:

List of Comparison Operators in Javascript

Operator NameSymbolDescriptionExample
let x = 5
Equal==Returns true if the operands are equalx == '5'(returns true)
Not equal!=Returns true if the operands are not equalx != '6' (returns true)
Strict equal===Returns true if the operands are equal and of the same typex === 5 (returns true)
Strict not equal!==Returns true if the operands are the same type but are not equal or are different typesx !== '5' (returns true)
Greater than>Returns true if the left operand is greater than the right operandx > 4 (returns true)
Greater than or equal>=Retruns true if left operand is greater than or equal to the right operandx > 5 (returns true)
Less than<Returns true if the left operand is less than the right operandx < 8 (returns true)
Less than or equal<=Returns true if the left operand is less than or equal to the right operandx <= 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

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! 😂

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.

Equal Operator vs. Strictly Equal Operator

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

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

Now you understand how equal comparison works and comparison operators JS. This same logic applies to not equal and strict not equal comparisons. You can also catch up on discussions surrounding comparisons and user questions on the js comparison operators stack.

Let's move on to logical operators.

Logical Operators

We use Javascript 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 in Javascript and then understand how this basic boolean logic works.

Logical Operators JS Table

Operator NameSymbolDescriptionExample
Logical AND&&Returns true if both the operands are true, else returns falsetrue && true
(returns true),
true && false
(returns false)
Logical OR| |Returns true if either of the operands is true; returns false if both are falsetrue | | 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:

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

OR vs. AND Logical Operators

When using the OR (||) logical operator, the result would be true even if one operand is true, even though the other operands are false. With the AND (&&) logical operator, we have seen that the result would be true if all the operands are true. Now, 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

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

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

I hope that now you understand the basics of logical operators JavaScript. 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.

Syntax for the ternary operator

condition ? expressionIfTrue : expressionIfFalse

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";

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.

Ternary Operator Example

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

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.

Ternary Operators Commonly Asked Questions

So that's about the ternary operator! Now for some commonly asked questions:

Is it good to use the ternary operator in Javascript?

So, there's been a long-running debate about whether it's advisable to use the ternary operator. Well, it's a useful tool that you may find yourself using from time to time as you write JavaScript code. In some cases, it can make statements more concise and easy to reason out. However, if someone is not familiar with the syntax, the code may look a bit confusing.

Which is better if-else or ternary operator?

The question of whether to use an if-else or ternary operator may boil down to the advantages that both ways offer. While the ternary operator offers a shorthand notation making code more compact, it can be less readable. The code may look messy if the expressions don’t fit into one 80-character line. Ternary operators are also more clear if a boolean value is expected or when setting values to variables. It may make more sense to use an if-else statement in all other cases, particularly if you want your code to be more readable. But which is going to be faster? Both statements are equally fast, but a ternary operator may be slowed down if additional computation is necessary to convert the logic.

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.

Checking the Types of Various Variables

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'

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

Now, there are two ways to use the typeof operator. You can either express it as

typeof operand typeof (operand)

Checking the Types for Functions, Methods & Properties with Typeof

So, really, the parentheses are optional. You can further find out the typeof for functions and methods.

console.log(typeof blur); // 'function' console.log(typeof eval); // 'function' console.log(typeof parseInt); // 'function' console.log(typeof shape.split); // 'function'

It’s also possible to find the typeof for predefined objects, though it’s not code you’ll find yourself regularly writing as you develop apps. But it can be fun to try them out:

console.log(typeof Date); // 'function' console.log(typeof String); // 'function' console.log(typeof Function); // 'function' console.log(typeof Option); // 'function' You can also use the typeof to find out the type of value held by properties, as illustrated by these static instances: console.log(typeof document.lastModified); // 'string' console.log(window.length); // 'number' console.log(typeof Math.LN2); // 'number'

Void Operator

In Javascript, type-checking is not strictly imposed as with other languages, and according to JS engines, a function will always return something. Undefined is usually the default return value of Javascript functions. Void signifies empty, and you should ideally use the void operator if the function doesn’t return anything. So, how should you use the void operator? Here is the basic syntax:

void function functionName() { //code to be executed }

You can also write the syntax with brackets as follows: void (expression); The function usually doesn’t take any parameters to evaluate. What are the possible applications of functions without any value to be returned? You may find yourself using the void operator in client-side Javascript, where you don’t require the browser to display the result. H2: In Operator The in operator is a type of relational operator used to carry out a comparison between operands. It simply checks whether a specified property exists in a specified object and returns a boolean value of true if it finds the specified property in the object; otherwise, it returns false.

You write the syntax as

propNameOrNumber in objectName,

The JavaScript in Operator Examples

So the proper name or number represents the property's name or its array index. An example of basic usage entails:

let dogs = ["Boxer", "Shepherd", "Chihuahua", "Poodle", "Dachshund"]; 0 in dogs; //returns true 1 in dogs; // returns true 3 in dogs; //returns true 7 in dogs; //returns false "Boxer" in dogs; //returns false (You are required to specify the index number)
//For custom objects, you can use the in operator as follows let myshoe = {brand: 'Jordans', Model: 'Air', year: 1987} 'brand' in myshoe //returns true 'year' in myshoe // returns true //You can also use the in operator for predefined or built-in objects 'PI' in Math // returns true

Instanceof Operator

The Instanceof operator checks if the type of object at runtime corresponds to the specified object type. Since it's used for checking the object type at run time, you can use it during exception handling. It returns a boolean value of true or false depending on the outcome.

Instanceof Syntax and Example

You write the syntax as:

objectName instanceof objectType

Here is an example that further illustrates its use:

var toDay = new Date (2021, 12, 20); if (toDay instanceof Date) { console.log('Happy Holiday!'); }

So, the statement executes after it determines that toDay is the Date object. You can also evaluate other JS objects such as Arrays.

Comma Operator

You'll find the comma operator in many programming languages, including Java, C, C++, and of course, JavaScript. It allows you to place multiple expressions in one place where a single expression is required. Its operands, the multiple expressions, will be evaluated from left to right, and the right outmost expression is returned.

Comma Operator Syntax and Example

The syntax entails:

Expression one, expression 2, Expression 3, Expression 4…..

And here is an example that illustrates its use:

function a() { document.write('I'+"</br>"); return 'I'; } function b() { document.write('am'+"</br>"); return 'am'; } function c() { document.write('girl'+"</br>"); return 'girl'; } var a = (a(), b(), c()); //Giving three expressions in one place Document.write (a); //Results //I //am //girl //girl

The output may be explained as follows: since expressions are evaluated from left to right, function a() is first executed, followed by b(), and c(), and lastly, the right outermost expression is return that's why you get two instances of “girl” in the results. You may use the comma operator in loops to accommodate multiple expressions

Delete Operator

You will use the delete operator to remove properties from the object. By completely destroying the property and freeing up resources, the property is no longer accessible and will return undefined. It can't affect variables or function names and must not be applied on built-in JavaScript object properties as it may cause the application to crash. If the delete operator is applied for a property that does not exist, it will not have any effect on the object and will return true.



Using the Delete Operator in Javascript

Here is an example showcasing how to use the delete operator:

<html> <body> <h2>JavaScript Delete Operator</h2> <p id="write"></p> <script> // Create an object: const car = {type:"Toyota", model:"NZE", color:"white"}; // Change a property: car.color = "black"; // Adding a property: car.owner = " Mary"; //Deleting a Property delete car.color; // Displaying the property: document.getElementById("write").innerHTML = "Car color is " + car.color + " and the car owner is " + car.owner; //returns Car color is undefined and the car owner is Mary </script> </body> </html>

Binary Bitwise Operators

The operators we have so far discussed have been manipulating objects, numbers, etc. A JavaScript bitwise operator treats its operands as 32-bit binary numbers. In 4-bit,1 becomes 0001, and 5 becomes 0101.

Binary bitwise operators return standard numerical values (64 Bits Javascript Numbers). Some programmers use bitwise operators instead of numbers for conversions or computations because they tend to be faster than Math or parseInst.

Operations are only restricted to numbers that can be expressed in 32-bit form within the range of -2147483648 to 2147483647. Some bitwise operators include:

You can get an in-depth look at JavaScript bitwise operations from the w3schools tutorial.

For instance, by applying ~ to 5, it’s inverted to -6 as follows:

00000000000000000000000000000101 to 11111111111111111111111111111010

Grouping Operator

In the first article, we talked about how expressions are evaluated based on operator precedence. For instance, in the expression (5+3 - 2), it was clear that 5 + 3 was first evaluated, then 2 subtracted from the result. But what if you wanted to subtract 3-2 and carry out the addition after? That's where you will use the grouping operator, and it’s simply a pair of parentheses.

Before we had: console.log (5 + 3 - 2); // 8-2

By adding the grouping operator, you’ll now have:

console.log (5 + (3-2)); // 5 + 1

It's that simple, and you can use it to override the default order of precedence for other operators, for instance:

console.log((1 + 2) * 3); //To give the addition precedence before the multiplication 3 * 3

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! 🤗

Related Posts