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 trialGUY SHIMON
1,301 Pointsif/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
Luke Glazebrook
13,564 PointsHi!
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') {
alert("Undefined.");
} else {
alert("Defined");
}
Jake Lundberg
13,965 PointsTo 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.
so:
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.
GUY SHIMON
1,301 PointsGUY SHIMON
1,301 PointsI 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?
Luke Glazebrook
13,564 PointsLuke Glazebrook
13,564 PointsBecause if you type null it just sets name to a string. So if you type in null it sets 'name' equal to "null".