Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript Introduction to Programming Control Structures If/Else

1,301 Points

if/else question

I have this code, like in the example:

var name = prompt("whats is your name")

if (name) {
  console.log("if block");
} else {
  console.log("else block");

If i reply nothing like he did, I get an "else block", but if I reply "null" or zero ("0") it stays as "if block". Why is that?

2 Answers


You aren't particularly checking anything with this. If you wanted to see whether the type was null you could do so using the code below.

var name = prompt("What is your name"?)

if (typeof name == 'undefined') {
} else {
1,301 Points

I didn't really get you.. What I actually wanted to ask is (if we go back to my code)- if when the prompt window pop up I type the word "null", why dosen't it replace the word "name" (as a ver) inside the prentices and produce a false E?

Because if you type null it just sets name to a string. So if you type in null it sets 'name' equal to "null".

Jake Lundberg
Jake Lundberg
13,965 Points

To try and be a little more clear...you are kind of asking a question that has not been touched on in this series yet; datatypes.

the prompt command returns a datatype called a string. for now, just think of a string as letters or words. so when you physically type in "null" the prompt window it is returning a string with the value of the word "null". This is completely different than the keyword null that Jim is talking about.


name = "null" // this is a truth'E' value because it is a string name = null // this is a false'E' value because keyword null mean no value

In the case of your code, it is handling you entering "null" the same way it is handling you entering your name.

The same goes for "0"

var number = "0" //this is a truth'E' value because it is a string number = 0 //this is a false'E' value because in a JavaScript conditional statement, 0 is equal to false.

I hope this helps.