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
A function is a collection of code that performs a task or calculates a value.
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
So functions are at the heart
of how JavaScript works.
0:00
A function is a collection of code that
does something as a function, right?
0:03
So for example, prompt and alert
0:06
are built in JavaScript functions you can
use over and over again in your program.
0:09
JavaScript also lets you
define your own functions.
0:13
To create a function,
you type the keyword function
0:16
followed by the name you want to give
the function, for example, myFunction.
0:20
Then a set of parentheses and
a set of curly braces.
0:25
In a function,
the Java script you place inside
0:29
the curly braces is run whenever
the function is activated.
0:32
Think of the code inside the braces as
a set of instructions that you want to run
0:36
each time the function is
referenced in your code.
0:39
So now I'm going to create a function
that contains the same prompt and
0:42
alert behavior we wrote
earlier in the console.
0:46
The function will ask for
a user's name and say hello.
0:48
So I'll name the function sayHello().
0:51
And between the curly braces, I'll add
the response variable and the prompt and
0:57
alert commands we wrote earlier.
1:02
So I'll type var response and
set it equal to prompt,
1:04
passing it the message, what is your name?
1:11
And below that I'll type alert and
1:19
I'll pass alert("Hello", space followed by
a plus sign then the response variable.
1:24
Plus sign and an exclamation mark.
1:32
So this functionality or
1:35
set of instructions is now
packaged up inside a function.
1:36
I'll give this file a save, and nothing
visually happens in the browser yet,
1:42
even when I refresh.
1:47
To activate the programming inside
a function, you call the function.
1:48
And to call a function and
run the code inside it, you write
1:53
the name of the function followed by
a set of parentheses and a semicolon.
1:56
So when you call a function,
you're telling the JavaScript interpreter
2:03
to jump to that function and
run the code inside it.
2:07
The syntax for
calling a function should look familiar.
2:10
Notice how alert and
prompt are also calls to the alert and
2:13
prompt functions built into JavaScript.
2:18
Over in the browser I'll refresh, and now
each time the sayHello function is called,
2:21
we'll see the dialogue
boxes pop up in the browser
2:26
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