Mechanics of Functions
A function is a series of statements that are grouped together to perform specific tasks.
Basics
function NAME(PARAMETERS,...) {
STATEMENTS;...
return VALUE;
}
- The
functionkeyword - Followed by a
name - Optional
parameters Statementsin curly bracesreturnstatement
Regular functions are created using the function keyword.
After this keyword, a name is given to the function. There are some specific rules. We'll talk about them in a bit.
In Parenthesis, you can specify optional parameters. That means that you can pass values to the functions and those become variables inside the function.
You can then add a series of statements inside curly braces. Each of those statements is usually separated by semicolons.
There's a special statement you can use inside a function to return a value when the function is executed.
Starting Code
const $ = document.querySelector.bind(document)
const output = 'Hello World'
$('#output').innerHTML = output
console.log(output)
Let's use CodeSpaces to try this out.
You'll notice that I've started you out with some code already. Let's talk about what that's setting up before we get into our function.
I've set up two sample ways to output our code.
const $ = document.querySelector.bind(document)
const output = 'Hello World'
$('#output').innerHTML = output
console.log(output)
You can see that I'm setting up a dollar sign variable that gives JavaScript access to the document. It's really just a shortcut ot the DOM or document object model.
Then I'm setting up a variable called output that I'm going to use to output the value.
Using our dollar sign object, we can target an element in the HTML with an ID of output.
The HTML for our page is in the canvas.html file, which you can get to in the explorer.
Then I'm using the innerHTML property to set the value of the element to our ouput variable. That's what writing the hello world to our page.
The other and much simpler way to output things is to use the console.log command. This is great for demos, but most of the time when I'm coding, I'm doing things on the page, so I wanted to show you both options.
Writing a Function
function add(a, b) {
const c = a + b
return c
}
const output = add(2, 2)
Let's use CodeSpaces to try this out.
Function Names
- Case sensitive
- camelCase
- Descriptive verbs
A couple of suggestions for naming functions.
First, be careful that variable names are case sensitive, so uppercase A in Add is differen than lowercase add
Typically function names are written in camelCase, First letter lowercase if the name has another word, it's in uppercase
Try to use descriptive verbs. I could have called my function addNumbers, but add is short enough.
By the way writing the function is called declaring the function, and using the function is called invoking the function, but things get really interesting when we dive into how this works, so lets keep going.