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 Basics (Retired) Making Decisions with Conditional Statements Introducing Conditional Statements

Loralie Flint
Loralie Flint
1,338 Points

i 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") };

app.js
var answer = prompt("What is the best programming language?");
if answer = ('JavaScript') {
  return alert("You are correct")
};
index.html
<!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

Loralie Flint
Loralie Flint
1,338 Points

i had just tried that and it worked thank you :)

Dave Harker
Dave Harker
Courses Plus Student 15,510 Points

Sadly 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

Dave Harker
PLUS
Dave Harker
Courses Plus Student 15,510 Points

Hi 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.