Functions
Lesson objectives
After this lesson students will be able to:
Describe why we use functions
Declare a function
Invoke a function
Properly name a function
Write an arrow function with a parameter
Write an arrow function with multiple parameters
Write an arrow function with a return statement
Break a problem down into steps
Describe why we use functions
Using functions is another application of DRY. Don't Repeat Yourself. With a function, you can store code that can be used conveniently as many times as you wish, without having to rewrite the code each time.
Defining a function
In Javascript there a few different ways of defining a function.
Function Declaration
Function Expression
Function Declaration
Function Expression
Function declarations and function expressions more-or-less do the same example thing, but there’s one subtle yet important difference between them.
Hoisting
Hoisting is a concept in JavaScript that essentialy means that all function delcarations are hoisted to the top of the Javascript code by the browser.
You can think of them as being brought to the top of the file. This means that no matter where you write a function declaration in your program, the declaration is known at the start of the program. Due to hoisting, you will be able to call a function declaration before you declare it in your program.
Other datatypes are also hoisted and we will talk about this at a later time. For right now this helps us understand the difference between a function expression and a declaration.
The concept of hoisting itself is a bit dated. In general, we won't want to declare functions before we use them. It will make our code more clear to invoke a function after we have declared it!
When to use a Function Expression or Function Declaration
Knowing when to use a function expression or declaration depends on the code you are writing. If you had to call a function before it was declared, this might be a good use case for a function declaration.
However, function expressions are very handy! They allow us to store anonymous functions (functions without a name) inisde of a variable for later use!
In fact, they are so useful that Es6 (one of the latest updates to the JS language) implemented a new kind of function that allows us to leverage the power of function expressions!
Es6 Arrow Functions
Arrow functions were introduced into the JS language for two primary reasons:
the need for shorter functions
the behavior of the
this
keyword (more on this later)
Always use const
to declare your functions. It would be a strange day when a function would need to be reassigned.
The code for printBoo()
will not run yet. The function needs to be invoked.
Invoke a function
Use one line of code to run multiple lines of code
Simply use the name of the variable and use parentheses to invoke the function.
If the parentheses are not included, the function will not run.
The invocation comes after the function definition. If you write it beforehand, it will be trying to invoke something that doesn't yet exist according to the interpreter.
This will work:
VS
This will not:
Exercise
Write a function
printSum
that will console.log the result of 10 + 10
Extra Reps
Write a function
printTriangle
that will print these pound signs to the console (there are 5console.logs
inside the function):Make it so that
printTriangle
will print the pound signs using a for loop (there is afor
loop and only 1 console.log inside the function).Make it so that when you can invoke the function with the number of pound signs to print (not just hardcoded to print 5)
Properly name a function
The variable you use for a function should contain a verb. Functions do something, most often:
getting data
setting data
checking data
printing data
If the purpose of your function is to check data, for example, use the verb check
in the variable name.
Example function that contains a conditional:
Functions should try to do only one thing
If a function, called checkInputLength
, does more than just check input, then it is a poor function.
Takeaway: Think about appropriate verbs to use in your function variable names. The verbs should indicate the one thing that the function does.
Write an arrow function with a parameter
The preceding function, checkInputLength
had a parameter called input
.
Functions can receive input that modify their behavior a bit. This input is called a parameter.
In the below example, the parameter is arbitrarily called name
. We can call our parameters whatever we want - whatever makes semantic sense.
Using concatenation I can put the input into a string:
When we invoke the function, we can specify the value of the parameter, this is called an argument:
We can continue to invoke the function with whatever arguments we want:
Each time, the output of the function will change to reflect the argument.
Argument vs Parameter
The argument is the input, the parameter is how the input is represented in the function.
Write an arrow function with multiple parameters
A function can take any number of parameters.
When you invoke the function, you generally want to supply the right number of arguments.
=> 16
Exercises
Write a function called
minusOne
that takes a parameternum
. Assuming the argument is a number, print the argument -1.Write a function
makeSentence
that takes three parameters and concatenates them into a fully formed sentence.=> 'Oh boy, do I want chimichangas or what?'
Extra
Write a function called
getLastElement
that takes a parameterarr
.Invoke the function with an array as the argument.
The function should print the last element within the array.
Hint:
arr[arr.length - 1]
Extra
Write a function
multiply
that takes three parameters and prints the result of multiplying all three numbers together.
Write an arrow function with a return statement
Functions can pass information back to whatever line of code invoked them.
A contrived example:
=> 18
Here ten()
gets replaced with whatever the return
statement is.
This is the main difference between return
and console.log()
. The output value of a function can not come from a console.log.
=> 10 => NaN
This is because it is trying to add 8 to undefined
.
A function is only defined if it has a return value.
The calculateArea
function has a return value of num1
* num2
. It does not just print to the console.
use the returned value of an invoked function
Sometimes a returned value will not appear in your console. This is normal. A return is not a console.log. To see the return value of a function, you will want to console.log the invocation:
=> -40
Since multiply
returns a value, we can use the return value of multiply
as an argument to an invocation of multiply
.
=> 32
return: stopping a function
RETURN sends the value of your function immediately. You can use return to terminate the function.
Example: will the function return 0 or 1? (It won't return both)
Break a problem down into steps
Write a function that will return true
if a word is a Palindrome, or will return false
if not.
Problem solve one step at a time
Each step might require research
Work in layers, one layer at a time. Don't jump ahead until each piece has been tested and works.
Determine if each step will require research, and research it.
reverse the word (how?)
check if the word is the same as the reverse (how?)
return true or false
Small problems
Write a function that takes two parameters (strings) and returns
true
(Boolean) if the two strings are identical,false
if not.Write a function that takes three parameters (numbers), sums them, converts the sum into a string and returns the string (eg.
"123"
)Use your google-fu to research converting a number into a string
Invoke the function a couple of times with different arguments each time
Experiment
What happens if you supply more arguments than there are parameters?
What happens if you supply fewer arguments than there are parameters?
This lesson was adapted from the SEIR-MAE repo lesson
Last updated
Was this helpful?