Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Preview
Start a free Courses trial
to watch this video
Let's use variables together with prompt()
and alert()
to create a simple program that asks the user for their name and replies with a short message that displays their name.
Resources
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
Now that we have a method for
collecting and storing information.
0:00
Let's see how to use variables to display
different messages in an alert box.
0:03
I'll use variable together
with the prompt and
0:08
alert to create a simple program
that ask the user for their name and
0:10
replies with a short message
that displays their name.
0:13
So in a console, I create a new
variable named response to store and
0:17
remember the response, or what a user
types into the prompt dialogue box.
0:23
So I'll set the value to prompt,
passing it the variable question.
0:28
Now I'll press Shift+Enter
to bring the cursor down.
0:34
And below the response variable,
I'll add alert and
0:38
pass it the message to
display as a string.
0:43
So the message will be Hello, followed by
the users name and an exclamation mark.
0:46
So the response variable is going to
hold the value of what the user types
0:51
into the box as a string, so
to combine the word hello and
0:57
the exclamation mark with what
the user types into the dialogue box.
1:01
I'll first type Hello and
a space between quotes,
1:04
followed by a plus sign,
and the response variable.
1:10
Then to add the exclamation
mark at the end,
1:15
I'll type a plus sign followed by
the exclamation mark inside quotes.
1:17
So here, I'm combining strings
1:23
using the plus sign which is a common way
of joining two or more strings together.
1:26
Combining strings together like
this is called concatenation.
1:30
It's JavaScript's way of adding strings
together to create a bigger string.
1:34
So now I'll press Enter
to run this program and
1:38
in the browser, I first see the prompt
dialog box asking, what is your name.
1:42
I'll type Guil and click OK.
1:47
Then I get the alert box with the message,
Hello Guil!, good.
1:51
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up