Bummer! This is just a preview. You need to be signed in with a Basic account to view the entire video.
Use Variables to Display Different Content1:55 with Guil Hernandez
Let's use variables together with
alert() to create a simple program that asks the user for their name and replies with a short message that displays their name.
Now that we have a method for collecting and storing information.
Let's see how to use variables to display different messages in an alert box.
I'll use variable together with the prompt and
alert to create a simple program that ask the user for their name and
replies with a short message that displays their name.
So in a console, I create a new variable named response to store and
remember the response, or what a user types into the prompt dialogue box.
So I'll set the value to prompt, passing it the variable question.
Now I'll press Shift+Enter to bring the cursor down.
And below the response variable, I'll add alert and
pass it the message to display as a string.
So the message will be Hello, followed by the users name and an exclamation mark.
So the response variable is going to hold the value of what the user types
into the box as a string, so to combine the word hello and
the exclamation mark with what the user types into the dialogue box.
I'll first type Hello and a space between quotes,
followed by a plus sign, and the response variable.
Then to add the exclamation mark at the end,
I'll type a plus sign followed by the exclamation mark inside quotes.
So here, I'm combining strings
using the plus sign which is a common way of joining two or more strings together.
Combining strings together like this is called concatenation.
So now I'll press Enter to run this program and
in the browser, I first see the prompt dialog box asking, what is your name.
I'll type Guil and click OK.
Then I get the alert box with the message, Hello Guil!, good.
You need to sign up for Treehouse in order to download course files.Sign up