✏️ 1.2.1.3 Practice: Writing Functions
Goal: In the "Writing Functions" lessons, we learned:
- When we define a function, this is called a "function declaration"
- When we execute a function's code, this is called "calling a function"
- The function body contains all of the statements that should be executed when a function is called.
- Functions can optionally have parameters — placeholder variables that let us pass data (like a string or number) into the function.
- When a function has parameters, we must pass in arguments for each parameter. The data we pass into functions are called arguments, and these are assigned as the value of the parameters.
- The
returnkeyword tells JavaScript to return the code to the right ofreturnoutside of the function. - Don't abbreviate variable names because it can make your code hard to understand to other people (including your future self).
Begin familiarizing yourself with writing custom functions in the DevTools console by completing the exercises detailed below. To make new lines and indentation in the DevTools console:
- Use
shift+enterto create a new line. - Use
tabto tab over multiple spaces for indentation. - To configure the console to use 2 spaces for indentation with
tab, in the DevTools window, go to Settings > Preferences > scroll to the Sources section > set "Default indentation" to 2 spaces.
Warm Up
- How do we call a function?
- How do we include an argument when we call a function?
- What is a parameter, and how do we create one in a function declaration?
- What is a return value? How do we tell our functions what value to return?
Code
Writing Custom Functions
Write a custom function for each of the following prompts. Then, call the function providing the necessary arguments to see if your function successfully returns the correct value.
- Write a function that takes somebody's name and returns a greeting that includes their name.
- Write a function to subtract two numbers. The function should return the result of the subtraction.
- Write a function to multiply two numbers. Then create a new function called
threeTimesto multiply three numbers together. - Write a function to divide two numbers. Then write a new function called
remainderto find the remainder of two numbers. Return the remainder as a string.