JavaScript

What is the difference between null and undefined in JavaScript

November 5, 2021

What is the difference between null and undefined in JavaScript

In this article we’ll clarify the difference between null and undefined, which are JavaScript values for two different situations, but they can be confused.

difference between null and undefined cover

Hey you programmer, okay? Let’s learn something new! 

The JavaScript language is quite complete, and we can use it for many purposes.

From web programming to data science, so of course we will have difficulties with some of its peculiarities

As it is the case with null and undefined, which in other languages often do not exist

And as you may already know, the difference is quite subtle, so it’s important to understand where one’s limit ends and the other begins

The best definition of undefined would be:

A primitive value, which we receive when a variable has not been previously assigned a value, it is often a programmer error.

And a good definition for null is:

A primitive value, which represents an intentional absence of a value, that is, the programmer induces null in the code.

In addition, some confusion arises when comparing these values, such as:

console.log(null == undefined)

We will receive true, because these two primitive values are false values, that is, converted to false in comparisons

So we can compare empty variables with null, which will get the same result from undefined

And to avoid further doubt, an example of inducing null would be to create an object that needs to start with a property x, but it has no initial value, for example:

let pessoa = {
 nome: "Matheus",
 idade: null
}

We now know the difference between null and undefined 

Conclusion

We learned that there are differences between null and undefined, although they are subtle

Basically, undefined is when a variable value is not defined

And null is an undefined value, but in an induced way, that is, the programmer put null in some object property, for example

Want to improve your JavaScript skills? Click here!

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x