How == and === are different in JavaScript
By Tan Lee Published on Dec 18, 2024 287
In JavaScript, == and === are both comparison operators, but they behave differently.
==
is the equality operator in JavaScript. It checks if two values are equal, but it performs type conversion if the values are of different types.
For example:
console.log(5 == '5'); // true (string '5' is converted to number 5) console.log(0 == false); // true (false is converted to 0) console.log(null == undefined); // true (considered equal in non-strict comparison)
===
is the strict equality operator in JavaScript. It checks if two values are equal and of the same type, without performing any type conversion.
For example:
console.log(5 === '5'); // false (different types: number vs string) console.log(0 === false); // false (different types: number vs boolean) console.log(null === undefined); // false (different types)
In summary, use ==
when you want to check for equality regardless of type, and use ===
when you want to check for both value and type equality. It is generally recommended to use ===
to avoid unexpected results caused by type conversion.
- How to use sweetalert2
- How to Pass string parameter in an onclick function
- How to format number with commas and decimal in Javascript
- What does 'use strict;' means in Javascript
- How to detect if caps lock is pressed in Javascript
- How to create a Custom Event in Javascript
- How to Check if an Object Has a Property Properly in JavaScript
- How to convert an Uint8Array to string in Javascript
Categories
Popular Posts
Freedash bootstrap lite
Nov 13, 2024
Gentella Admin Template
Nov 14, 2024
tsParticles Authentication Template
Nov 11, 2024
Responsive Animated Login Form
Nov 11, 2024