Home > Web Front-end > JS Tutorial > JavaScript Equals: JavaScript '===' vs '=='Comparison Operator

JavaScript Equals: JavaScript '===' vs '=='Comparison Operator

Susan Sarandon
Release: 2024-10-18 06:24:30
Original
270 people have browsed it

In JavaScript, the equality operators "==" and "===" are used to compare two values, but they work differently in terms of how they handle data types. Here’s a simple explanation:

1. == (Loose Equality):

The JavaScript equals or loose equality operator ( == ) checks if two variables or values are equal. It returns true if two values are of equal value, even if they're of different types. Conversely, it returns false if the values aren't of equal value.

JavaScript Equals: JavaScript ‘===’ vs ‘==’Comparison Operator

Here, JavaScript converts the string '1' into a number 1 and then compares them, so it returns true.

  • What it does: It checks if two values are equal, but ignores the data type.
  • Type conversion (coercion): JavaScript automatically converts one or both values to the same type before comparing them.

Others Example:

i). 0 == false is true (because false is converted to 0)
ii). null == undefined is true (they are considered loosely equal)

Problem: This automatic type conversion can sometimes lead to unexpected results, so it’s generally considered less reliable.

2. === (Strict Equality):

The strict equality (===) operator checks whether its two operands are equal, returning a Boolean result. Unlike the equality operator, the strict equality operator always considers operands of different types to be different.

JavaScript Equals: JavaScript ‘===’ vs ‘==’Comparison Operator

Here, JavaScript does not convert the string '1' into a number. Since 1 is a number and '1' is a string, it returns false.

  • What it does: It checks if two values are exactly equal, including both the value and the data type.
  • No Type conversion: It does not perform type conversion; the types must match for the comparison to return true.

Others Example:

i). 0 == false is false (because 0 is a number and false is a boolean)
ii). null == undefined is false (they are of different types)

Summary:

  • == (loose equality) compares values after converting them to the same type.

  • === (strict equality) compares values without any type conversion.

The above is the detailed content of JavaScript Equals: JavaScript '===' vs '=='Comparison Operator. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template