How == and === are different in JavaScript
By Tan Lee Published on Dec 18, 2024 259
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:
1 2 3 |
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:
1 2 3 |
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
11 Things You Didn't Know About Cloudflare
Dec 19, 2024
Materio Admin Template
Nov 13, 2024
10 Common Mistakes ASP.NET Developers Should Avoid
Dec 16, 2024
How to secure ASP.NET Core with NWebSec
Nov 07, 2024