Functions

Back

Learning Goals

  • Explain the purpose of functions
  • Use built-in methods on appropriate data types
  • Define and invoke functions in JavaScript
  • Use and explain the flow of data with arguments and parameters
  • Describe the purpose of a return value

Vocabulary

  • method
  • function
  • call, invoke
  • define, declare
  • return value
  • parameter
  • argument

Defining Our Own Functions

Functions are structures in JavaScript that are fundamental to writing a program. A function is essentially a package of instructions for a program to follow. The JavaScript language has many methods built-in that you’ll explore later in this lesson. Built-in methods are great and you will use them regularly as a developer. There will also be times when you need to write your own method to solve a unique problem in the application you are building or maintaining.

Syntax for Defining a Function

To define (or declare) a function, the following syntax must be used:

  • The function keyword declares a new function.
  • The function name follows the function keyword and is determined by the person writing the code. It’s best if the name describes what the function does.
  • A set of opening and closing parentheses ().
  • A set of opening and closing curly brackets {}, which will create the code block.
  • One or more lines of code inside the curly brackets - this is where the “instructions” live. These instructions describe what the function should do when it is called.
  • The value that follows the return keyword is the data that the function will return when it is called.
function greetATexan() {
  return "Howdy, partner!";
}

After defining a function, nothing will appear to happen. The interpreter that reads the JavaScript code will read it, and be aware of that set of instructions, but it won’t carry out those instructions until it is explicitly told to do so.

Syntax for Calling a Function

To instruct the interpreter to carry out the instructions in a function, the developer must write code to call (or invoke) that function. To call a function, the following syntax must be used:

  • The function name
  • A set of opening and closing parentheses ()
  • To follow conventions and best practices, the line should end with a semi-colon ;
greetATexan();

Naming Conventions

Since functions provide action to a program, they should be named accordingly; it’s best practice to start them with a verb. Like variables, JavaScript functions should use camelCase when they involve more than one word and should be written carefully to describe their role specifically without being overly verbose.

Examples of function names that follow best practices:

  • getUserInput
  • displayFollowers
  • addTwoNumbers
  • findLongestName

A Function Metaphor

Often, we want to use a function to perform an action on or with a piece of data. Think of your function like a machine with inputs and outputs.

If this were a cookie machine, for example, the machine would take in all of the raw ingredients (eggs, flour, sugar, etc.) and perform some steps to make the cookies:

  1. Mix ingredients to make dough
  2. Place dough balls on a baking sheet
  3. Bake at 350 degrees for 10 minutes
  4. Let cookies cool
  5. Serve the cookies on a plate

We can imagine that our cookie machine would do all of those steps and then give us back freshly baked, warm cookies!

Let’s expand this example to any kind of machine. We give the machine the raw materials, it does something with those materials, and then returns the final product. This is very similar to what we are doing with our own functions. We can give the function some piece of data or information (or even multiple pieces of information) and then the function does something with that information and spits out a return value.

Waterfall

Look at the function call below and make a guess about how this might be different from the previous method example.

  greetATexan("Kaitlyn");
  // => "Howdy, Kaitlyn!"

Type your answers in the chat and be ready to submit when it's time!


Without possibly having all the information about JavaScript syntax, you probably made some connection as to what might be happening with the previous code snippet. The greetATexan() function was called, but this time, we were able to dynamically change the name of the person we were greeting!

Arguments and Parameters

Functions can be more powerful and dynamic when they have additional information about the situation each time they are called. We must follow a specific syntax to “pass information” into a function:

  • In the function definition, parameter(s) must be declared. Parameters act like placeholder variables that can be accessed inside the function. As such, variable naming conventions should be followed when naming parameters.
  • In the function call, argument(s) - the actual data - must be provided. Since this is actual data, it must be in the form of a valid JavaScript data type, such as a String or Number.
  • The number of arguments passed in should match the number of parameters declared.
function greetATexan(name) {
  return `Howdy, ${name}!`;
}

console.log(greetATexan("Kaitlyn"));
// => "Howdy, Kaitlyn!"

console.log(greetATexan("Brian"));
// => "Howdy, Brian!"

Note: You’ll notice that we are using the console.log() statement with the function call this time. This allows us to also see the return value of the greetATexan function printed to the console, but it is not necessary. The code greetATexan("Kaitlyn") by itself does return the string “Howdy, Kaitlyn!”, but if we want to see it printed in the console, we will need to use console.log() along with the function call.

The following code snippet illustrates a function definition and call that involves 2 pieces of data, both Numbers.

function subtract(max, min) {
  var difference = max - min;
  return difference;
}

console.log(subtract(10, 3));
//  => 7

Pair Practice

In your Breakout room, the person with the longest first name will Drive. The other will Navigate. The Driver should screenshare a replit and the Navigator should keep these instructions up.

  • Write a function named greetAnAnimal. This method should declare one parameter, a String, and when called, should return a string with a greeting for the specific animal that was passed in as an argument.
  • Write a function named multiply. This method should declare two parameters, both Numbers, and when called, should return the product of the two Numbers. Call the method several times with different arguments and run the code to ensure it's working as expected.


Return Values

It’s important to note that JavaScript functions are not required to have a return value. The return statement is optional in JavaScript functions. As a result, it is entirely possible to write a JavaScript function that only performs a series of actions without returning anything at all.

function makeFreshPesto() {
  console.log("Buy ingredients: basil, parmesan, romano, olive oil, pine nuts, garlic, salt, pepper");
  console.log("Pulse basil and pine nuts");
  console.log("Add garlic and cheeses");
  console.log("Slowly pour in oil");
  console.log("Season");
}

makeFreshPesto();

However, it is often preferable to have our function return a value, because it increases its utility. Let’s take a look at an example.

function add(num1, num2) {
  var sum = num1 + num2;
  console.log(sum);
}

add(5, 2);
//  => 7

This add function adds the numbers together and logs the sum to the console. This is cool, but what if I wanted to use that number in a different way? The example below shows how I might modify that function, so that it simply returns the sum instead of logging the value to the console. Then, I can do all kinds of different things with that return value! In this way, functions that return a value are more flexible than functions that only log to the console.

function add(num1, num2) {
  var sum = num1 + num2;
  return sum;
}

console.log(add(5, 2));
//  --> 7
console.log(`The sum of 5 and 2 is ${add(5, 2)}.`)
//  --> "The sum of 5 and 2 is 7."

Key Point: Up until now, we’ve used the console.log() statement to see values printed to the console. Be careful not to confuse what you see in the console with the return value of the function or method – these are two different things. We use console.log() to see data in the console, but what we see in the console is not always the return value.


Storing a Return Value

The examples we’ve looked at so far call the function and execute the code within the function, but the return values go nowhere/can never be used in the program again. Many times, we’ll store the return value of a function in another variable, as modeled below:

function add(num1, num2) {
  return num1 + num2;
}

var sum1 = add(10, 4);
var sum2 = add(7, 20);

console.log(sum1);
console.log(sum2);

Pair Practice

In your Breakout room, the person with the shortest first name will Drive. The other will Navigate. The Driver should screenshare a replit and the Navigator should keep these instructions up.

  • Write a function named getAge. This method should declare one parameter, a Number, representing a birth year.
  • When called, the function should calculate the person's approximate age. Let's not worry about birth month or day. 😉
  • The function should return a Number representing the person's age.
  • Call the function several times with different arguments and store the return values in variables.
  • Print a sentence that says, "You have lived ___ years of life!" with each variable interpolated into the String.


Key Points Summary

  • A function is a packaged set of directions. If the function is never called, it will never run. And a function can be called many times, if needed!
  • The number of arguments in a function call must match the number of parameters in the function definition.
  • Function names should start with a verb and use camelCase.
  • Return values are optional in JavaScript functions. If a return value is included in a function, that value after the return keyword is the data that will be returned when a function is called.


Self-Teach

Part of what you’ll experience at Turing is learning a technical topic on your own. Practicing this skill at Turing will get you prepared for the job where you will do this often.

Take time between now and your next session to self-teach the following section.

Warm-Up for Built-In Methods

Exploration: PART 1

Fork, then run the code in this replit and observe the output.

Discuss: How did each line of code, produce each respective line of output? Which parts make sense, and which are confusing?


Built-In Methods

Both methods and functions are sets of instructions that perform a specific task. The only difference is that a method is associated with an object, while a function is not. For now, we’ll use the term method to describe the pre-packaged functions that are built into the language and are called on a specific data type. The term function is used to describe a block of code that a developer designs to perform a particular task. Let’s explore some of those built-in methods available to us in JavaScript.

The code snippet below is an example from the previous Exploration activity:

console.log("Hello World".startsWith("H"));

To describe the code snippet in English, one could say, “the startsWith() method is being called on the string ‘Hello World’.” Since “Hello World” does start with “H”, true will be the return value. The console.log() command prints that return value of true to the console.

In this particular example, the utility of the startsWith() method is to determine if a String starts with a specified character, or not. It answers the question with a Boolean (true or false). The benefit of having this method built into JavaScript is if a developer needs to check if a String starts with a specific character, they can use the startsWith() method anywhere they need to check. If they didn’t have a pre-packaged method, they’d have to write several lines of code involving logic, every time they want to check if an integer is odd. Reusability is what makes methods and functions so powerful.


Exploration: PART 2

In the same replit from the first exploration, comment out the code from Part 1, and uncomment the code under Part 2.

  • Run the code.
  • Discuss: What is different about this from the first set of method calls? How did each line of code, produce each respective line of output? Which parts make sense, and which are confusing?


The following code snippet demonstrates that a method can be called on a variable assigned to data:

var newString = "Hello World";
console.log(newString.toUpperCase());

To describe the code snippet in English, one could say, “the first line declares a variable called newString and the second line calls the toUpperCase() method on the newString variable.” As a result, the method will return a String object where any letter character in the original String stored in newString will now be uppercase. The console.log() command prints that return value of "HELLO WORLD" to the console. However, it’s important to note that the original data stored in newString is not modified permanently.


Exploration: PART 3

In the same replit, comment out the code from Part 2, and uncomment the variable declarations and first method call under Part 3.

  • Run the code and read the error message carefully. Work to make sense of what the problem is.
  • Comment out that method call, and uncomment the next one. Run the code and read the error message carefully. Work to make sense of what the problem is.
  • Repeat the previous step until you've run the code for each method call.
  • Modify the existing code so that it runs without errors.
  • Write down a 1-3 sentence explanation of your main takeaway from this exploration.


Key Points

  • A method is a package of instructions that once defined, can be reused as many times as needed.
  • A method can be called on a variable that holds data.
  • JavaScript provides built-in methods for each data type, but not every method will work on every type of data.


Check For Understanding

  • Complete the work in the CFU repository.
  • Add a link to your respository under a new section of your Mod 0 Gist called Functions.





Back