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 trial

JavaScript JavaScript Foundations Variables Null and Undefined

Ashton Morlote
Ashton Morlote
5,517 Points

Why would I want to give a variable no value?

I am sorry if this is explained in the video and I missed it, but why would I want to give a variable no value? I am a bit confused about the importance of the "null" and "undefined" values.

Any clarification will help to get me straightened and continue learning.

Thank you.

Alexander Costa
Alexander Costa
11,464 Points

undefined = it never existed;

null = it exists but has no value;

or best described here

http://stackoverflow.com/questions/801032/why-is-null-an-object-and-whats-the-difference-between-null-and-undefined

I am not a 100% sure but i am guessing their will be times when you want something to have no value.

2 Answers

I can think of two possible situations. 1) if you want a loop to continue executing until a situation becomes true, you would initialize it to a null value. 2) you want the user to enter a a specific field on a form or take a certain action on a site, you can set an initial value to null. Once the user takes the desired steps, you set the value from null to some truthy state and the user can continue.

Wajeeh Hassan Qureshi
Wajeeh Hassan Qureshi
8,631 Points

Well, when we define a variable and set its value to either undefined/null we most likely want to be able to change it, only if a certain condition is true or not.