We know many operators from school. They include addition +, subtraction -, multiplication *, etc.
As with all other programming languages, JavaScript includes operators as well. An operator performs some operation on single or multiple operands (data value) and produces a result. For example 1 + 2, where the + sign is an operator and 1 is the left operand and 2 is the right operand. + operator adds two numeric values and produces a result of 3 in this case.
JavaScript includes the following type of operators.
Arithmetic Operators
Comparison Operators
Logical Operators
Assignment Operators
Conditional Operators.
Arithmetic Operator
Arithmetic operators are used for performing mathematical operations between numeric operands. They are things like addition, multiplication, subtraction, and so on. Arithmetic operators are something that we've all used before. If we'd want to perform a mathematical operation, we'd like to use arithmetic operators.
Arithmetic operators perform arithmetic on numbers.
+ Addition
- Subtraction
* Multiplication
/ Division
() Grouping operator
% Modulus (remainder)
++ Increment numbers
-- Decrement numbers
//Addition
10 + 13; // 23
//Subtraction
23 - 11; // 12
//Multiplication
12 * 5; // 60
//Division
55 / 10; // 5.5
//Modulo
11 % 5; // 1 (remainder of 11/5)
//-----------Increment and Decrement------------//
5++; // 6
7--; // 6
//-------------Exponentiation----------------//
2 ** 3; // 8
Comparison Operators and Equality
You've most likely heard of greater than >, less than < or equal to \==.
Comparison Operators compare two values and return the boolean value true or false. The return value of a comparison operator is ALWAYS going to be a boolean value.
The topic of Equality in JavaScript is closely connected to the comparison operators.
const a = 5; const b = 10; //to check whether a value is greater than the other value console.log(a > b); //to check whether a value is greater than or equals to the other value console.log(a >= b); //to check whether a value is less than the other value console.log(a < b); //to check whether a value is less than or equals to the other value console.log(a <= b); //-------Equality Operator------- //to check whether two values are equal console.log(a == b); //to check whether two values are not equal console.log(a != b); //But more often we are going to see and use the strict equality and strict inequality operators. console.log(a === b); console.log(a !== b);
Everything that we've covered is pretty straight
forward. The only thing that I'd like to take a
deeper look at is strict vs loose equality. What
are the differences and when should we use
each option? Let's cover that next!
Strict vs Loose Equality
Equality is a fundamental concept in JavaScript.We say two values are equal when they are the same value. For example:
console.log('JavaScript' === 'JavaScript'); //true
console.log(2 === 2); //true
Note that we use three equal signs to represent this concept of equality in JavaScript. JavaScript also allows us to test loose equality. It is written using two equal signs. Things may be considered loosely equal even if they refer to different values that look similar, an example would be the following:
console.log(5 == "5" ) // true
Strict Equality
The strict equality method of comparison is a preferred option to use because its behaviour can be easily predicted, which leads to fewer bugs and unexpected results. The JavaScript interpreter compares the values as well as their types and only returns true when both are the same.
console.log(10 === "10" ) // false
The code above will print false because even though the values seem to be the same, they are of different types. The first one is of type String and the second is of type Number.
Here's just one short thing that I wanted to show you. If we strictly compare objects, we're never going to get true. Let's test it out:
console.log({} === {}); // false
// we get false, even though they have the same type and content, weird
// the same thing happens for arrays as they are actually objects under the hood
console ([] === []); // false
For the sake of simplicity, we're not going to go into too much depth about non-primitive data types like objects and arrays. That is a rather complex topic on its own. Because of that, I will write a separate blog called Value vs Reference. In there we're going to explore the mentioned inconsistencies of the equality operator. Now let's move on to the loose equality.
Loose Equality
We write loose equality using double-equal signs. It uses the same underlying logic as Strict equality except for a minor, yet huge, difference.
The loose equality doesn’t compare the data types. You should almost never use loose equality.
JavaScript has two sets of equality operators: \=== and !== , and their evil twins \== and !=.
The good ones work the way you would expect. If the two operands are of the same type and have the same value, then === produces true and ! == produces false.
The evil twins do the right thing when the operands are of the same type, but if they are of different types, they attempt to change the values. The rules by which they do that are complicated and unmemorable. These are some of the interesting cases:
'' == '0' //false
0 == '' //true
0 == '0' //true
false == 'false' //false
false == '0' //true
false == undefined //false
false == null //false
null == undefined //true
/*------------Using the == opeartor-----------*/
// true, because 'true' is converted to 1 and then compared
true == 1;
// true, because the string of "5" is converted to the number 5 and then compared
5 == "5";
/*------------Using the === opeartor-----------*/
true === 1 // false
5 === "5"; // false
//Thats how it should be
Note: Always use the === operator for equality
Logical Operators
Logical operators are used for combining two or more conditions. JavaScript includes three logical operators:
&& - AND
|| - OR
! - NOT
Complete knowledge of logical operators requires the knowledge of if/else statements and truthy and falsy values. For now, we're just going to cover the syntax of logical operators and then we're going to come back to them to see them in full action after we cover the two mentioned topics!
AND Operator (&&)
Double ampersand && is known as AND operator. It checks whether ALL OPERANDS are true values. And if they are true, it returns true, otherwise, it returns false.
console.log(true && true); //true
console.log(true && false); //false
console.log(false && false); //false
//we can also pass multiple conditions like:
console.log(true && true && false); //false
OR Operator (||)
|| is known as an OR operator. It checks whether AT LEAST ONE OPERAND is a true value. And if there is at least one true, it returns true, otherwise, it returns false.
console.log(true || true); //true
console.log(true || false); //true
console.log(false || false); //false
//we can also pass multiple conditions like:
console.log(true || true || false); //true
NOT Operator (!)
An exclamation sign ! is known as NOT operator. It reverses the boolean result of the condition.
console.log(!true); //false
console.log(!false); //true
As you can see, the not operator simply converts the boolean false to true and the boolean true to false. This was just an introduction to these logical operators. They are used really really often in real JavaScript applications and I'm excited to show you their real uses once we learn about if statements and truthy and falsy values!
Arithmetic Operators
An assignment operator assigns a value to its left operand based on the value of its right operand.
Would you believe me if I told you that you not only know what an assignment operator is but that you've been using it this whole time? The simplest form of an assignment operator is the \= equal sign used for assigning values to variables:
const age = 20;
//This is the assignment operator
We can also join the assignment operator with one of the arithmetic operators:
let number = 5;
number += 5; //same as: number = number + 5
number -= 5; //same as: number = number - 5
number *= 5; //same as: number = number * 5
number /= 5; //same as: number = number / 5
//The addition assignment can also be used in Strings
let string = "Hello";
string += ", I am John";
console.log(string); //Hello, I am John
That's it when it comes to assignment operators, you're basically a pro at them!
Conclusion
In conclusion, understanding operators in JavaScript is essential for any developer looking to create robust and efficient applications. Operators are the building blocks of programming languages and play a crucial role in performing various operations on data types. By mastering different types of operators, such as arithmetic, assignment, comparison and logical operators, developers can create complex and sophisticated applications with ease. Whether you're a beginner or an experienced developer, having a strong grasp of operators in JavaScript is a valuable skill that can help you write clean and efficient code.