JavaScript: Functions

This is the anatomy of a function:

1//       |   A     |    B     |
2function doTheThing(cat, pants) {
3  var result = "Hello, " + cat + ", you are " + pants + " years old"
4
5  return result // C
6}
7
8/*
9  A:
10    1. The name of the function
11    2. Just like when naming a variable, you can give it whatever name you like
12
13  B:
14    1. The function parameters
15    2. Just like when naming a variable, you can give them whatever name you like
16
17  C: This is where the function returns a value to wherever the function was called
18*/

Examples

Defining a Function Without Calling

1function doTheThing() {
2  console.log("Hello")
3}
4
5// The function was never called, so it does not execute

Defining a Function and Executing It

1function doTheThing() {
2  console.log("Hello")
3}
4
5doTheThing()
6// Prints: "Hello"

Multi-line function w/ Variable

1function doTheThing() {
2  var name = "John"
3  console.log("Hello " + name + ", welcome home!")
4}
5
6doTheThing()
7// Prints: "Hello John, welcome home!"

Function w/ 1 Parameter

1function doTheThing(cat) {
2  // var cat = "John" <-- This is how parameters work, but it's invisible
3  console.log("Hello " + cat + ", welcome home!")
4}
5
6doTheThing("John")
7// Prints: "Hello John, welcome home!"

Function w/ 2 Parameters

1function doTheThing(cat, pants) {
2  // var cat = "John" <-- This is how parameters work, but it's invisible
3
4  // var pants = 35 <-- This is how parameters work, but it's invisible
5
6  console.log("Hello " + cat + ", you are " + pants + " years old!")
7}
8
9doTheThing("John", 35)
10// Prints: "Hello John, you are 35 years old!"

Function w/ Return Statement

1function doTheThing() {
2  return (5 * 2)
3}
4
5var result = doTheThing() // Stores: 10
6
7console.log(result) // Prints: 10

Function w/ 1 Parameter and Return Statement

1function doTheThing(cat) {
2  return (cat * 2)
3}
4
5var result = doTheThing(5) // Stores: 10
6
7console.log(result) // Prints: 10

Function w/ 2 Parameters and Return Statement

1function doTheThing(cat, pants) {
2  return (cat * 2) + pants
3}
4
5var result = doTheThing(5, 3) // Stores: 13
6
7console.log(result) // Prints: 13

Function w/ 1 Parameter and Multiple Executions

1function doTheThing(cat) {
2  return ("Hello " + cat + ", welcome home!")
3}
4
5console.log(doTheThing("John"))
6// Prints: "Hello John, welcome home!"
7
8console.log(doTheThing("Jane"))
9// Prints: "Hello Jane, welcome home!"
10
11console.log(doTheThing("Chad"))
12// Prints: "Hello Chad, welcome home!"

One reason is that we frequently need to reuse functionality

Another reason is that it putting a process inside of a function gives us the chance to provide the process with a meaningful name that can help the reader understand what the code is doing