DEV Community

Kelliann Lafferty
Kelliann Lafferty

Posted on • Updated on

Comparing variables in Javascript

As I go through the job search process, I like to keep track of questions that I've been asked that I don't exactly know the answer to but feel like I should. To alleviate these feelings, I'm making an effort to keep track of these questions and then write short posts on them to hopefully:

  1. Solidify these concepts for myself, so I'll be more prepared in the next interview

  2. Help another developer understand these concepts so they may be more prepared if they are asked these questions in the future

Question

What is the difference between '==' and '==='?

Answer

These are known as comparison operators and Javascript has both type-converting and strict comparisons.

Type-converting comparisons (e.g. ==) will first convert the elements to the same type (if they aren't already) and then make the comparison.

1 == 1 // true
'1' == 1 // true
1 == '1' // true
0 == false // true
0 == null // false
0 == undefined // false

var object1 = {'key' : 'value'}, object2 = {'key': 'value'}
object1 === object2 // false

null == undefined // true 

Strict comparisons (e.g. ===) will only return true if the elements on both sides are of the same type.

3 === 3 // true
3 === '3' // false

var object1 = {'key' : 'value'}, object2 = {'key': 'value'}
object1 == object2 // false

null === undefined // false 

Follow-up Question

What would be the output of "null == undefined" and "null === undefined" in Javascript and why?

Answer

As you can see from the code above, based on the comparison operator, one of these is true, whereas the other one is false.

console.log(typeof null) // object
console.log(typeof undefined) // undefined

Null == Undefined, with a type-converting equality operator, returns true because Null and Undefined are two different data types in Javascript. Null is considered an object, and Undefined is considered a type of undefined. Since these are two separate data types, the '==' converts null and undefined to the same type and then compares them and since they both represent an empty value, they are considered equal in the abstract sense.

As for Null === Undefined, this is a false statement, because they are inherently not the the same data type (object vs. undefined) and thus, this is strictly false.

Happy coding! :)

More resources:

https://developer.mozilla.org/en/US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators

https://levelup.gitconnected.com/javascript-null-vs-undefined-2acda986f79f

Top comments (0)