Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
I'm trying to make an id searcher which does a thing when you input the right id. However, the JavaScript if statement always runs. How?
In JavaScript, using the assignment operator (=) instead of comparison operators (== or ===) in an if statement causes the condition to always evaluate as true. This is because assignment returns the assigned value, which is typically truthy.
The Problem: Assignment vs Comparison
When you accidentally use = in a condition, you're assigning a value instead of comparing:
let searchId = 10001;
let currentId = 10002;
// Wrong: This assigns searchId to currentId and always runs
if (currentId = searchId) {
console.log("This always runs! currentId is now:", currentId);
}
// Right: This compares the values
if (currentId === searchId) {
console.log("This only runs when they match");
}
This always runs! currentId is now: 10001
Correct ID Search Implementation
Here's how to properly implement an ID searcher using the strict equality operator (===):
var details = [
{
id: 10001,
name: "John"
},
{
id: 10002,
name: "Bob"
},
{
id: 10003,
name: "Carol"
},
{
id: 10004,
name: "David"
}
];
var searchId = 10003;
var found = false;
for (var index = 0; index < details.length; index++) {
if (details[index].id === searchId) {
console.log("ID " + details[index].id + " found: " + details[index].name);
found = true;
break;
}
}
if (!found) {
console.log("ID " + searchId + " not found");
}
ID 10003 found: Carol
Comparison of Operators
| Operator | Purpose | Example | Result |
|---|---|---|---|
= |
Assignment | if (x = 5) |
Always true (assigns 5 to x) |
== |
Loose equality | if (x == 5) |
True if x equals 5 (with type coercion) |
=== |
Strict equality | if (x === 5) |
True if x equals 5 (same type and value) |
Modern Approach Using Array Methods
For a more elegant solution, consider using Array.find():
var details = [
{ id: 10001, name: "John" },
{ id: 10002, name: "Bob" },
{ id: 10003, name: "Carol" },
{ id: 10004, name: "David" }
];
var searchId = 10003;
var result = details.find(function(item) {
return item.id === searchId;
});
if (result) {
console.log("Found:", result.name);
} else {
console.log("ID not found");
}
Found: Carol
Conclusion
Always use comparison operators (== or ===) in if statements, never assignment (=). The strict equality operator (===) is recommended as it prevents unexpected type coercion issues.
Advertisements
