Functions
Objectives
Describe a situation where you would use:
A function with a return value
A function without a return value
A function with a parameter
Describe the difference between printing and returning
Write a function with and without a return value
Write a function with a parameter
Write a function that operates on two or more parameters
Identify the scope of variables inside and outside functions
Defining a function
A function is a module that can store and invoke code. When writing repetitive code, we can isolate code into functions in order to reduce repetition. For example, if we needed to say "Hello World" to the screen multiple times, we can create a function like so.
Note that a function is assigned to a variable, and we can call the function by taking the variable name and appending parentheses to the end of the function variable.
Parts of a function
We can also create functions that accept parameters, and use those parameters as variables in the function.
Defining a function with a parameter
Defining a function with two parameters
Functions can have multiple parameters, separated by commas.
Printing and returning are different
Note that functions can have input via parameters. They can also have output as return values. Returning values from a function is denoted by the keyword return
. Also, return values are optional.
Note that printing something to the screen using console.log
is not the same as returning values.
Declaring functions
There are two different ways to declare a function
The difference between these two is that the first one is defined at run-time, meaning that if we try to call the function before it's declared, an error will be thrown:
The second declaration is defined at parse-time, so we can call the function wherever we'd like.
Despite being more flexible, the former declaration that assigns the function to a variable is more common when developing Node applications.
Exercises
What is the return value of this function when called?
How would the function above be modified if the user wanted to pass in an object of lightsabers, like this one?
Last updated