Hello👋. Remember, operators in Javascript are symbols that are used to perform mathematical, logical, relational operations, amongst others. Today, we’d be focusing on relational operators.
Relational operators in Javascript are used to compare two values and determine whether they’re equal, not equal, greater than, less than, or greater than or equal to each other. These operators are often used in conditional statements and other places where you need to compare two values. Most times, relational operators gives the result true or false. i.e. outputs are mostly in a Boolean format.
Comparing two numbers.
console.log (5>6) //false
console.log (7>6) //true
Let’s compare variables,
let data = 7 > 6
console.log (data) //true
let data = 7 < 6
console.log (data) //false
Let’s compare two equal values,
let data = 6 <= 6
console.log (data) //true
The data above can be saved in variable. For the purpose of learning, let’s understand via the example below:
let x = 6
let y = 6
let data = x >= y
console.log (data) //true
Comparing two strings
let x = "pen"
let y = "book"
let data = x > y
console.log (data) //true
Why is the output true?
What happens in the above is that every character or letter has a unique number. They are called ASCII values. (Short for American Standard Code for Information Interchange, ASCII is a standard that assigns letters, numbers, and other characters unique values for encoding in computers.)
Capital B in ‘book’ comes before capital P in ‘pen’, thus, P in ‘pen’ is greater.
let x = "pen"
let y = "pencil"
let data = x > y
console.log (data) //false
Pencil is greater than pen because it has longer characters.
Comparing a number and a string.
let x = "2"
let y = 1
let data = x > y
console.log (data) //true
The output is ‘true’ because the “2" in string is converted into number before comparison takes place.
let x = "2"
let y = 3
let data = x > y
console.log (data) //false
Output is false because ‘2' is converted from a string to a number.
Assignment operator
The equal to ‘=’ symbol represents the assignment operator. It is used to assign values.
Equality Operator
The double equal to ‘==’ symbol is used as the equality operator. It is used to compare values. When used in Javascript, it gets converted into other formats.
let x = 3
let y = 3
let data = x == y
console.log (data) //true
Strict Equality Operator
The ‘===’ symbol is used to prevent conversion and coercion of values. When you want to compare values, use the symbol ‘===’. Example:
let x = 3
let y = 3
let data = x === y
console.log (data) //false
The double equal to ‘==’ symbol is risky because it only checks values, not the type. However, the triple equal to ‘===’ symbol checks the type as well as data.
I hope you learnt a thing or two.
See you next time.