How to compare operands (values) in JavaScript

in Code Write a comment

Learn the basics of comparing two values in JavaScript to see if they are equal.

Comparing values in JS can be tricky e.g.:

1 == "1" // true
1 === "1" // false

Let me explain how to better understand it.

There are both strict and non-strict comparison operators in JavaScript.

Strict operator (===)

A strict comparison operator or a triple equals (===) checks whether both operands contents and types match.


Hi, I'm Renat πŸ‘‹

➜  


Abstract comparison (==)

Unlike strict comparison, abstract comparison converts the operands to the same type and only compares their contents.

Demo

console.log(1 == 1); // true

console.log("1" == 1); // true

console.log(1 === 1); // true

console.log("1" === 1); // false

If you know a shorter version or want to add another example please share it in the comments below.
Cheers,
Renat Galyamov

Want to share this with your friends?
πŸ‘‰renatello.com/javascript-comparison-operators

PS: Make sure you check other JavaScript tutorials, e.g. shortest β€œHello, world!” app in JavaScript frameworks.

A collection of UI components for
Bootstrap 4/5 and Vue.js

Get now

Write a Comment

Comment