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 trialLoralie Flint
1,338 Pointsi cant get my conditional statement to work i used if statement
var answer = prompt("What is the best programming language?"); if answer = ('JavaScript') { return alert("You are correct") };
var answer = prompt("What is the best programming language?");
if answer = ('JavaScript') {
return alert("You are correct")
};
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JavaScript Basics</title>
</head>
<body>
<script src="app.js"></script>
</body>
</html>
2 Answers
Tim Dalton
Full Stack JavaScript Techdegree Student 13,159 PointsTry changing if answer = ('JavaScript') to
if (answer == 'JavaScript') {
Edit: Woops! forgot to use double ==
Dave Harker
Courses Plus Student 15,510 PointsHi Loralie,
You are using an assignment operator ( = ) instead of a comparative operator, which in this case needs to be either the equality ( == ) or identity/strict equality ( === ) operator, to compare user input with pre-defined string. Also you need to put the entire condition check within the brackets ().
Change this:
var answer = prompt("What is the best programming language?");
if answer = ('JavaScript') { // The problems are here.
return alert("You are correct")
};
to this:
var answer = prompt("What is the best programming language?");
if (answer == 'JavaScript') {
return alert("You are correct");
};
Hope that helps,
Dave.
Loralie Flint
1,338 PointsLoralie Flint
1,338 Pointsi had just tried that and it worked thank you :)
Dave Harker
Courses Plus Student 15,510 PointsDave Harker
Courses Plus Student 15,510 PointsSadly this is not a correct solution as it will return True and execute the 'alert' no matter what the user enters due to the assingment operator being used instead of a comparative operator. So, while it works if the user types JavaScript, it also works if they type Aardvark. Obviously, not a desired outcome.
Please see solution and reasoning in alternate answer below. There are a few little common 'gotchas' like this in programming so don't sweat it ... just take a note of them and keep on coding!
Kind regards,
Dave