- -- operator
- -= operator
- ++ operator
- += operator
- Accessing and setting content
- Array concat() method
- Array indexOf()
- Array length
- Array pop()
- Array shift
- Arrays
- Booleans
- Braces
- Callback function
- Calling the function
- Class
- Closure
- Code block
- Comment
- Conditions
- Console
- Constructor
- Creating a p element
- Data types
- Date getTime()
- Destructuring
- Else
- Else if
- Enum
- Equals operator
- Error Handling
- ES6
- Event loop
- Events
- Extend
- Fetch API
- Filter
- For loop
- forEach()
- Function
- Function bind()
- Function name
- Greater than
- Head element
- Hoisting
- If statement
- includes()
- Infinity property
- Iterator
- JSON
- Less than
- Local storage
- Map
- Methods
- Module
- Numbers
- Object.keys()
- Overriding methods
- Parameters
- Promises
- Random
- Reduce
- Regular expressions
- Removing an element
- Replace
- Scope
- Session storage
- Sort
- Splice
- String
- String concat()
- String indexOf()
- Substring
- Switch statement
- Template literals
- Ternary operator
- Title
- Type conversion
- While loop
JAVASCRIPT
JavaScript Equals: The Equality Operator in JS
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.
Quick Answer: How to Use Equality Operators in JS
JavaScript has two main sets of equality operators: loose equality (==
and !=
) and strict equality (===
and !==
).
- Loose Equality (
==
): Checks if two values are equal after attempting to convert them to a common type. This is called type coercion. - Loose Inequality (
!=
): The opposite of==
. It returnstrue
if two values are not equal, also after type coercion.
Loose Equality Example (==
):
console.log(5 == '5'); // true, because the string '5' is converted to a number
Loose Inequality Example (!=
):
console.log(1 != true); // false, because true is converted to 1
For modern JavaScript, it is strongly recommended to use the strict equality (===
) and strict inequality (!==
) operators instead. They do not perform type coercion and prevent common bugs.
How to Use the Equality Operator in JavaScript
The equals operator consists of two equals signs. Here's the basic syntax for using the equality operator:
let a = '5';
let b = 5;
console.log(a == b); // Outputs: true because '5' becomes 5 before the comparison
==
: The symbol for the equality operator.a
,b
: The variables or values to compare.
When to Use the Equality Operator
The equality operator is useful for comparisons when types already match or you specifically want type conversion.
Conditional Logic
In web forms, where user inputs are strings, the loose equality operator can simplify comparisons with expected numeric values. Before comparing, the ==
operator performs type coercion to convert the string to a number.
let ageInput = document.querySelector('#age').value; // User inputs '30' as a string
if (ageInput == 30) {
console.log('Thank you for confirming your age.');
}
Filtering Data
When processing JSON data from APIs, ==
can filter or process elements where type conversion might be necessary:
fetch('https://api.example.com/products')
.then(response => response.json())
.then(products => {
let filtered = products.filter(product => product.quantity == '10'); // Product quantity might come as a string
console.log(filtered);
});
Asserting Values in Unit Tests
During unit testing, you might use the equality operator to check outputs that are subject to type coercion:
let result = functionUnderTest('5', 5); // Function that returns 10 as a number or string based on input types
console.log(result == 10); // True if result is '10' or 10, useful for flexible testing scenarios
Examples of Using the Equality Operator in JavaScript
E-Commerce Applications
As an example, consider special offers within an e-commerce website. You might use ==
to ensure that the number of items in the cart matches the offer requirements, even if the data types differ:
let itemsInCart = ['apple', 'banana', 'cherry']; // Items as an array of strings
let cartCount = document.querySelector('#cart-count').textContent; // Cart count from webpage as string
if (cartCount == itemsInCart.length) {
console.log('Eligible for a discount!');
}
Educational Software
In educational software, comparing student responses in different data formats to the correct answers stored in a system:
let correctAnswer = 4; // Correct answer as a number
let studentAnswer = document.querySelector('#answer').value; // Student's answer as a string from input field
if (studentAnswer == correctAnswer) {
console.log('Answer is correct!');
}
Learn More About the Equality Operator
JavaScript Not Equal Operator
The not equal operator (!=
) checks if two values aren't equal, converting types if necessary. Like the loose equality operator, !=
can treat seemingly different values as equal if they're logically equivalent.
let accessLevel = '200';
if (accessLevel != 200) {
console.log('Access level is not 200.'); // This will not execute because '200' is coerced to 200
} else {
console.log('Access level is 200.'); // This will execute
}
== vs. === in JavaScript
JavaScript features a loose equality operator (==
) and a strict equality operator (===
). The choice between double equals and triple equals as a comparison operator depends on your needs for type coercion.
==
can be useful with forms, where any numerical values you capture are usually strings. In most cases, however, ===
is a better and safer choice to ensure type safety and avoid unintended behavior.
let quantity = 0;
let userInput = '0';
console.log(quantity == userInput); // Outputs: true
console.log(quantity === userInput); // Outputs: false, highlighting the importance of type safety
Key Takeaways for JavaScript Equality
==
Converts Types: The loose equality operator (==
) will try to convert operands to the same type before comparing them. This can lead to unexpected results (e.g.,null == undefined
istrue
).!=
Also Converts Types: The loose inequality operator (!=
) also performs type coercion before checking if the values are different.===
is Safer: The strict equality operator (===
) checks for both value and type equality without any type conversion. It is the recommended operator for most situations.!==
is Also Safer: The strict inequality operator (!==
) checks if values are not equal in either value or type.- Default to Strict: As a best practice in modern JavaScript, always default to using
===
and!==
to prevent bugs caused by automatic type coercion. Only use==
and!=
if you have a specific reason to perform a loose comparison.
Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.