DEV Community

Cover image for WHAT IS EQUALITY IN JAVASCRIPT?
Maakai123
Maakai123

Posted on

WHAT IS EQUALITY IN JAVASCRIPT?

*In this short article, you will understand
1) How to use Equality in JavaScript
2)Understand the basics of Logic operators *

What is Equality and how to use them in JavaScript?

In JavaScript, equality refers to comparing two values to see if they are the same.(==,===)
Do not be confused, when you see const toDay = saturday, in JavaScript this means declaration of variable or assignment and not equality.

JavaScript has two ways of comparing two values

1)Loose Equality Operator ==
The Loose equality operators does type coercion, which means converting a string to a number before comparing them.
'18' == 18, ouput: true
the above means string == number is true

2) Strict Equality (===):
The best way to compare values in JavaScript.
The strict equality operator compares both the values and their types without type coercion (meaning without converting a string to a number).
It returns true only when both sides are exactly true.

example '18' === 18 = false
18=== 18 = true

Examples

const age = '20'
a) if(age === 20) console.log(You can drive)

b) if(age == 20) console.log(you can drive)

From the above two if statements (a) is strict so the code will not be executed.

If statement (b) Is Loose, and it supports type coercion which means string '20' is equal to number 20. The you can drive will be executed.

Example 2
a)

const foodNumber = '25'
if(foodNumber == 25) console.log('Number 25 is Rice')

output:Number 25 is Rice

The above code will be executed because == converts foodNumber which is a string to a number 25 and immediately compare them.

b)

const foodNumber = 25
if(foodNumber == 25) console.log('Number 25 is Rice')

output:Number 25 is Rice

The above code will also be executed because 25 (number) is equal to 25(number).

Example 3
a)

const foodNumber = '25'
if(foodNumber === 25) console.log('Number 25 is Rice')

This code will not be executed
Because foodNumber is a string and === don't support type coercion.

Top comments (1)

Collapse
 
overflow profile image
overFlow

Welcome to our lovely dev.to. full of love and code.

please complete your seemingly very very "short Article".