== and ===

If == looks at the value irrelevant of its type.
=== also checks if the type is the same.

Why can’t I do the following?

let mood = ‘sleepy’;
if (mood == sleepy) {
console.log(‘Time to sleep’);
}

I thought that == would check the word sleepy in all data types and find out that it’s a string and then work. Why doesn’t it?

1 Like

Hi there.

I’m going to presume that this is in relation to an exercise on Codecademy? (It looks a little familiar.)

If so, I think you’re bumping into the fact that the learning environment and the validation method for your attempt can be very pedantic. A lot of the time in the JavaScript material here, the lesson expects that you’ll use the “identity” comparison operator (===) and refused to accept the equality comparison operator (==) regardless of the fact that either would produce an acceptable result.

TL;DR - the material, for better or worse, effectively assumes you’ll default to the === operator. (JavaScript is a loosely typed language anyway, with very few built in types and a lot of things simply being an object… so in many cases the choice you make between == and === is moot from my experience with it so far.

1 Like

Thanks for the reply. So what you’re saying is that both can really be used?

here:

if (mood == sleepy) {

sleepy is an undefined variable.

strict equality (===) is always prefered when possible, otherwise you might get unexpected comparison results.

1 Like

When doing something like
let test = ‘Yes’;
if (test == ‘Yes’); {
console.log(‘Works’);
}

it works regardless if I use === or ==. I’m still a bit confused on the use of each.
In addition to this. Someone in another thread mentioned that == will not compare the types. In that case, for the code I posted earlier, why wouldn’t if(mood == sleepy) work? Since it’s ==, shouldn’t it think ‘let me see if the value of mood is sleepy as a string’? Sorry for overcomplicating this. I tend to overthink things.

there is a difference between working and good/best practice.

things get confusing when working with numbers, numbers as string and other data types:

console.log([] == 0) // true
console.log([] === 0) // false
console.log(1 == '1') // true
console.log(1 === '1') // false

ideally, understanding JS type conversion helps, but that is more complex matter

2 Likes

This fully explains it. Thank you so much! :grin:

1 Like