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

Paul Barron
Paul Barron
6,595 Points

console.log(typeof myVar === "undefined")

What is it's practical use? Why do I need to know this? When will this come in handy?

Are you referring to just typeof myVar === "undefined" or the entire console.log line?

3 Answers

Here's a good page that contains the "===" comparison operator: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators

Knowing that a variable is undefined or null could be an important part of a function. For example:

You create a function that takes inputs and assigns them to variables (Name, Age, and Location), however Location is optional. For the sake of this example, imagine a form on a website. There are 2 text inputs, and 1 dropdown list for the Location.

The Rules: Both inputs (Name, Age) have to be filled out, and there's the option to opt-out of Location. Name has to be a string, Age has to be a number, and Location has to be selected or opted out of (null), not undefined.

To check for these rules in javascript, you'd probably use the typeof operator. Say Name and Age where filled out correctly, but someone didn't select their Location, and they didn't opt-out (set to null) via a checkbox, they simply left it empty. Via if (typeof === "undefined"), you could know that, and not allow them to continue, instead displaying to a user the appropriate error message.

Does that make sense to you? I hope so :P

Paul Barron
Paul Barron
6,595 Points

What you said Bryan, just the whole "===" and while I'm at it, why even have ==? I understand that it tells me if the var is truly undefined, but would I need to know this? What are some real instances that might bring this up?

Paul Barron
Paul Barron
6,595 Points

YESSSSS!!! Bingo! Thanks a lot!

:) Perfect! Good luck with the rest of the course. It gets much more fun in the jQuery section.