Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialmauriciofiorenzano
Courses Plus Student 1,968 PointsNull and Undefined uses?
Why would I left a variable with no value? I do not fully understand why this part if JS is important. Just thinking logically every variable need to be defined by a value, isn't it?
3 Answers
Dino Paškvan
Courses Plus Student 44,108 PointsThink of it this way: null
is an intentional lack of value, while undefined
is unintentional lack of value.
There are many reasons why you'd want to set something to null: resetting some counter or property, to show that a certain input field hasn't been filled and so on.
undefined
is JavaScript's way of telling you that you've declared a variable, but you haven't set it to anything. It's more of a warning mechanism than something that you'd set manually (although even that is possible).
And because null
and undefined
are distinct, you can do checks in the code to see whether the lack of value is intentional or an error.
Laura Cressman
12,548 PointsMy intuition is that it can be useful to create a variable that you might use later. When you set the value to null, then you have a variable that you can later put information into. An example that comes to mind is an if else statement, where in some cases you want the variable to have a value other than null, while in other cases you want the variable to return null. Setting the variable to null initializes it so that you can later work with it. Something else that I'm thinking of is objects, where some objects may have a property that isn't null, while the property is null for other objects.
mauriciofiorenzano
Courses Plus Student 1,968 PointsThank you Laura I'm starting to understand more but still have some way to go in order to fully comprehend this part of JS, let see if I see Null and undefined more clear in the process.