NEW Try Zapier integration to connect Dasha instantly to thousands of the most popular apps!
JavaScript Operators: Beginner's Guide Part 2
Sumudu Siriwardana, Developer Advocate
8 min
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 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.
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.
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.
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 Name
Symbol
Description
Example
Logical AND
&&
Returns true if both the operands are true, else returns false
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:
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 trueconstsarahLovesCoffee = true; // AconstcoffeeCupIsEmpty = false// Bconsole.log(sarahLovesCoffee || coffeeCupIsEmpty); // true//Both operands are falseconstsarahLovesCoffee = false; // AconstcoffeeCupIsEmpty = false// Bconsole.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.
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.
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.
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(typeofDate); // 'function'console.log(typeofString); // 'function'console.log(typeofFunction); // 'function'console.log(typeofOption); // 'function'Youcanalsousethetypeoftofindoutthetypeof value held by properties, as illustrated by these static instances:console.log(typeof document.lastModified); // 'string'console.log(window.length); // 'number'console.log(typeofMath.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:
voidfunctionfunctionName() {//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:
letdogs = ["Boxer", "Shepherd", "Chihuahua", "Poodle", "Dachshund"];0indogs; //returns true1indogs; // returns true3indogs; //returns true7indogs; //returns false"Boxer"indogs; //returns false (You are required to specify the index number)
//For custom objects, you can use the in operator as followsletmyshoe = {brand:'Jordans', Model:'Air', year:1987}'brand'inmyshoe//returns true'year'inmyshoe// returns true //You can also use the in operator for predefined or built-in objects 'PI'inMath// 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:
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.
functiona() { document.write('I'+"</br>"); return'I'; } functionb() { document.write('am'+"</br>"); return'am'; } functionc() { document.write('girl'+"</br>"); return'girl'; } vara = (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.
Syntax:
delete Object.property
Using the Delete Operator in Javascript
Here is an example showcasing how to use the delete operator:
<html><body><h2>JavaScript Delete Operator</h2><pid="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:
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!