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 JavaScript Basics Making Decisions in Your Code with Conditional Statements Program Multiple Outcomes

how to would i add user input and still run this code?

gill is console logging it and assigning a variable but what if i want the user to input the information

2 Answers

Cameron Childres
MOD
Cameron Childres
Treehouse Moderator 11,715 Points

Hi Vikrant,

A simple way to do this would be using prompt(), much like in the previous video:

const weather = prompt('What is the weather?');

With the code as written in the video the only acceptable answers will be 'sun', 'rain', or 'snow'. Otherwise the code will run the final else statement.

If you want to view the response outside the console you could replace console.log() with alert().

These methods work fine for testing but they aren't the most elegant ways for users to interact with a site. Stick with the courses and you'll learn more ways of receiving user inputs and displaying information, such as through text/dropdowns and changing HTML on the page with JavaScript. I hope this helps!

Thank you but how would we write the if else or it would be written still the same?

Cameron Childres
Cameron Childres
Treehouse Moderator 11,715 Points

The logic stays the same so you wouldn't need to do anything besides swap out console.log() for alert(). All that you're doing is changing where the message is displayed. Like this:

const weather = prompt("What's the weather?");

if ( weather === 'sun' ) {
  alert("It's sunny, so I'm going swimming.");
} else if ( weather === 'rain' ) {
  alert("It's raining, so I will read a book.");
} else if ( weather === 'snow' ) {
  alert("It's snowing, so I'm going sledding.");
} else {
  alert("I don't know what I'm doing today.");
}