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
You'll usually pass information to a function to change how the function works, using parameters.
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
Just like you're able to pass information
like a message into prompt and alert,
0:00
you'll commonly pass information to a
function to change how the function works.
0:05
To do this,
0:10
you add what's called a parameter inside
the parentheses when creating a function.
0:10
So now let's change sayHello to a function
that accepts a custom greeting and
0:15
displays it to the user.
0:21
First, I'll change the function name to
0:22
sayGreeting to better to describe
the purpose of the function.
0:26
And this function will take one parameter,
I'll call it greeting.
0:29
Then I'll pass greeting into alert,
I'll simply copy and
0:35
paste it and replace Hello Wwith greeting.
0:40
And I'll combine it with
response using a plus sign.
0:44
Now I wanna display a space and
a comma between the greeting and name.
0:48
So I'll add them inside quotes
0:53
with a plus sign before and
after this new set of quotes.
0:58
So the greeting parameter
works just like a variable.
1:04
Notice how I'm using
it inside my function,
1:07
just like any variable,
like response, for example.
1:09
So now, each time I call this function,
1:13
it's going to expect
information passed into it.
1:16
So right below the function,
let's call sayGreeting.
1:19
And between the parentheses,
I'll pass the string Good morning.
1:27
Passing information to
a function call like this
1:33
is also called passing
an argument to a function.
1:36
I'll give main.js a save.
1:39
Over in the browser, I'll refresh.
1:41
I'll type Guil into the box, click OK, and
1:45
it returns an alert with the message
Good morning, Guil, cool.
1:49
Now if I go back to my program and
change the message to Have a good day.
1:53
Refresh.
2:05
It now displays an alert with
the message have a good day, Guil.
2:07
Good, so as you can see using parameters
with functions makes them more flexible.
2:10
We can pass different values and
get different results.
2:15
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