Intro to functions
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
Parts of a
The key word
Followed by the name of the function.
Followed by a set of parentheses with no space between the name and the left parentheses. (We'll put stuff in those parentheses later.)
After the parentheses, there is a space, followed by a left curly-brace.
"use strict";. This is required for all from now on.
And finally, a right curly-brace on its own line. This terminates the function. Note that this closing brace is always vertically aligned with the letter "f" in the word "function" at the beginning of the function.
.js file. They are located in the
js directory located in our unit folder. Go ahead and take a look, it's full of
.js files. You will have a one for each project part, lab, and exercise.
Inside each of the
.js files, a controller function is set up for you. Here's what one looks like. There is a
document.write() method built into each controller function that outputs the location of the file. This is there, so you can see the function call working. Once you start working in the file, this
document.write() should be removed.
Below, you can see there is no output - our function is not working. Let's fix that.
1 2 3 4 5 6 7 8 9 10 11 12
Getting the function to work¶
Just like in our previous units, we need to call the function. It's also referred to as invoking or firing the function. However we refer to it, we need to make the code run. We call our function in the HTML file between
The name of the function is
Following the name of the function, you need parentheses and a semicolon.
Now that I've called the function in the HTML document, you can see we have our output!
Use the Chrome View > Developer > Page Source (right-click > View Page Source) menu item and view the top of the file we're looking at right now. You should see this line:
<head>tag lets the browser know where to look for the file containing the function. It is also a
No amount of experimentation can ever prove me right; a single experiment can prove me wrong. -Albert Einstein