I’m working on a function that is supposed to check if a variable is equal to "this is a string" when run and logs true or false. This is what I tried:
let e = "this is string"
function stringCheck(){
if(e = "this is a string"){
console.log(true)
} else{
console.log(false)
}
}
It didn’t work. It logs ‘true’ even when I make it so e equals something completely different. I tried switching ‘true’ and ‘false’ and that made it so it only logged as ‘false’ no matter what e equaled. I can’t figure out what’s wrong with the code.
>Solution :
You are making an assignment instead of a comparison in your function. You must use the correct operator. In this case I replaced the single = with a ===:
function stringCheck(){
if(e === "this is a string"){
console.log(true)
} else{
console.log(false)
}
}
In JavaScript you have two different equality operators:
== compares values and makes automatic castings if necessary
2 == '2' // true. The string gets converted to number.
=== compares value AND type:
2 === '2' // false. String and number aren't equal.