Functions

Back

Learning Goals

  • Explain the purpose of a function
  • Declare and invoke a function
  • Use and explain the flow of data with arguments and parameters

Vocabulary

  • argument
  • call, invoke
  • define, declare
  • function
  • parameter

Functions

Functions are structures in JavaScript that are fundamental to writing a program. A function can be thought of as a package of instructions for a program to follow.

Syntax for Defining a Function

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

  • The function keyword to communicate that JavaScript should expect the next pieces of information
  • The function name. This is developed by the person writing the code
  • 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
function displayFunctionSkeleton() {
  // statements 
  // go 
  // here
}

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 ;
displayFunctionSkeleton();


Play Around

Fork this replit and run the code.

Change the String inside the console.log statement. Run the code.

Add two more console.log statements below the first one. Run the code.

The code currently calls the function one time. Call the function three times. Run the code.

Change the name of the function in the declaration only. Run the code. What is the problem?

Change the name of the function in the calls. Run the code.


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


An Analogy

One way to think about functions is as a recipe for a meal:

  • Defining the function can be compared to writing a recipe, or taking a screenshot of a recipe on our phone. It has the ingredients and directions, but that alone won’t cook the meal.
  • Calling the function can be compared to following the directions of the recipe to cook the actual meal. If you never choose to cook the recipe - no harm, but it was a waste of time to write it out. The meal could be cooked once, twice, or many times!

While the code snippet below illustrates a very contrived function, it is valid JavaScript:

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();


Practice: Define and Call a Function

Referring to the lesson and your notes is encouraged, but for your learning's sake, do not copy-and-paste!

In a replit file or a file in Atom, define a function named printGreeting. Inside the code block, write a console.log statement that prints a friendly greeting. Then, call the function.

Run the code. You should see the console.log statement in your console.


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 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 (String, Number, Boolean, etc.)
  • The number of arguments passed in should match the number of parameters declared.
function makeDinner(genre) {
  console.log(`Tonight, we will make a delicious ${genre} dinner.`);
}

makeDinner("Italian");
// --> "Tonight, we will make a delicious Italian dinner.

makeDinner("Mexican");
// --> "Tonight, we will make a delicious Mexican dinner.

The following code snippet illustrates a function definition and call that involves 3 pieces of data.

function addThreeNums(first, second, third) {
  var sum = first + second + third;
  console.log(sum);
}

addThreeNums(1, 2, 3);
//  --> 6

Practice: Arguments and Parameters

  1. Fork this repl.it
  2. Before running the code, predict what will print to the console. Then, run the code.
  3. Change the order of the arguments being passed into the function call on line 5. Re-run the code and observe the output. Then revert the changes you made.
  4. Change the order of the parameter names declared on line 1. Re-run the code and observe the output. Then revert the changes you made.
  5. Change the order of the parameters that are interpolated in the console.log statement. Re-run the code and observe the output. Then revert the changes you made.
  6. Synthesize: What do you know about parameters and arguments, specifically regarding the order they are provided in? (Be ready to verbally explain this to your peers)

For the next activity, referring to the lesson and your notes is encouraged, but for your learning's sake, do not copy-and-paste!

  1. In a new replit file or a file in Atom, define a function named greetMe that declares two parameters, a first and last name. Inside the code block, write a console.log statement that prints a sentence greeting a person using both first and last names.
  2. Then, call the function with appropriate arguments.
  3. Run the code. You should see the console.log statement in your console.
  4. On a new line of code, call the function again, using different arguments.
  5. Run the code.
  6. On a new line of code, call the function one more time, using different arguments.
  7. Run the code.


Key Points Summary

  • A function is a packaged set of directions. If the function is never called, it will never run. It 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.


Check For Understanding

Complete the work in the CFU repository and submit your work using the submission form.





Back