JavaScript #11 ~ Equality Operators: == vs. ===

HJ's Coding Journey·2021년 6월 8일
0

[Learn] JavaScript

목록 보기
12/20

In previous posts, I talked about the importance and functions of logical operators (>, <). But, what if two values are equal to each other. Besides logical operators, there are also equality operators to compare two values that are equal to each other.

First, we have the strict (===) equality operator that compares two or more operands by checking the equality between the values as well as their types. On the other hand, we have the loose (==) equality operator that compares two or more operands by converting ehir value to a common type first and then checking for the equality between them. The strict equality only returns 'true' if the values and the type both match with the other operand. The loose equality allows more leniency between operands and allows various types to return true.

Because of this leniency with loose operators, there are more chances to encounter unexpected bugs and errors within code. As such, developers almost always tend to use the strict equality, due to its type reasonable type handling function.

const age = '18';
if (age === 18) {
  console.log('You just became an adult :D'); // strict equality
if (age == 18) {
  console.log('You just became an adult :D'); // loose equality

There is also the not equal (!==) operator that checks whether two or more operands are not equal to each other. This method also has the same functionality as the ones mentioned above

const age = '18';
if (age !== 18) {
  console.log('You are not and adult yet!);
}
profile
Improving Everyday

0개의 댓글