If you're new to JS you might wonder what the title even means. Well there are actually 3 different ways that the = is used in javascript, based on how many of them you put in a row.
The two "normal ones"
So, there are two "normal" situations you have probably seen the = in javascript, assignments and checking conditions. Assignments are used to assign variables, and conditionals is what you do when you're using an if statement, or while loops. Here's an example of both
authorized = false; // This is an assignment (uses 1 =)
if (authorized == true){ // This is a conditional (uses 2 =)
console.log("You're good to go")
} else{
console.log("Bad boi, get out of here")
}
It seems like this should be all you need... right?
The problem child
There is a third operator that uses 3 = and is another form of comparison, but more strict. Take this example
age = "23"
if (age == 23){
console.log("Based")
} else {
console.log ("Less based")
}
Now in the first example it was clear that authorized is false, and the second message would print. In this case however the == will actually convert the string to an integer, and then make the comparison, which means "Based" would be printed instead.
Consequences
This is very weird for most people, and == actually does other conversions (these happen with a lot of operators) depending on types that are being compared. This can lead to unexpected behaviours in your code, such as
1 == true // This is true
// So when doing calculations
2-1 == true // This is true
"29"-28 == true // this is true
That last one the - operator converts "29"
to 29
, then subtracts 28
from it (leaving 1
), which is true
. JavaScript to be fair isn't the only language that does this on comparisons (1==True
in python as well), but it is the only one (that I know of) that solves this in a weird way. The === operator is a strict comparison in JavaScript. This means it will check if something is equivalent to something else without doing type conversions. So
// ==
1 == true // This is true
// So when doing calculations
2-1 == true // This is true
"29"-28 == true // this is true
// ===
1 === true // this is false
// So when doing calculations
2-1 === true // this is false
"29"-28 === true // this is false