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
Sebastian Nitu
8,616 PointsSome help with conditionals in JavaScript, please?
Hello,
So I was playing around with the code, you know, to make it "sink in" better. I was just about to pass on to "loops" when i encountered this strange situation:
If I execute this code, regardless of the string value assigned to name it will pass it to the if block even though the value is not "David".
var name = prompt("what is your name?");
if (name = "David") {
alert("Howdy partner!");
} else {
alert("Hello " + name + ", want some cake?");
console.log(name + " wants some cake!");
}
The strange part is that if I use a "not equal to" operator "!=" it works but different. If the name is not David, then it will go to say "Howdy partner!" but if the name is "David" it will say "Hello "David" want some cake?"
var name = prompt("what is your name?");
if (name != "David") {
alert("Howdy partner!");
} else {
alert("Hello " + name + ", want some cake?");
console.log(name + " wants some cake!");
}
The question here is, why isn't the first example working?
Why is the second example working?
How should I have done this?
4 Answers
Daniel Matthew
2,625 PointsI couldn't tell you the particulars, but your code should be looking to compare rather than assign. So your code becomes
if (name == "David") {}
(or even if (name === "David"){})
Sebastian Nitu
8,616 PointsThanks Daniel, what is the difference between "==" and "==="?
Thanks once again!
Rick Yentzer
5,885 PointsThe difference between == and === is that == will do type conversion. For instance:
if (2 == "2") {
// this code WILL run
}
Even though typeof(2) = number and typeof("2") = string, when using == JS will coerce the data type in order to compare the values if possible.
if (2 === "2") {
// this code WILL NOT run
}
The === is for strict comparison. It will not attempt to convert data types. Therefore 2 != "2";
Here is a good explanation: http://www.impressivewebs.com/why-use-triple-equals-javascipt/
Daniel Matthew
2,625 PointsThanks Rick - you were able to put that much more succinctly than I.