JavaScript Functions Worksheet

Question 1

What is a function, and why would you ever want to use one in your code?

A function is a small piece of code that does a specific job. You use functions to save time by reusing the same code instead of writing it over and over. They help make your code easier to understand and change. Functions also keep your code neat and organized.
Question 2

What do you call the values that get passed into a function?

The values that get passed into a function are called arguments.
Question 3

What is the 'body' of a function, and what are the characters that enclose the body of a function?

The body of a function is where the function does its work. It's the code that runs when you use the function. The body is usually enclosed by curly braces { }.
Question 4

What does it mean to 'call', or 'invoke' a function (note that 'calling' and 'invoking' a function mean the same thing)?

To call or invoke a function means to use it. When you call a function, you are telling the program to run the code inside that function.
Question 5

If a function has more than one parameter, what character do you use to separate those parameters?

If a function has more than one parameter, you use a comma to separate them.
Question 6

What is the problem with this code (explain the syntax error)?


function convertKilometersToMiles(km)
    return km * 0.6217;
}
                

The function convertKilometersToMiles(km) line is missing the opening curly brace { to start the function body. the function body must be enclosed in curly braces { }.
Question 7

In the code below, there are two functions being invoked. Which one returns a value? Explain why you know this.


const name = prompt("Enter your name");
alert("Hello " + name + "!");
                

The prompt() function returns a value because it gets input from the user, while alert() just shows a message and doesn't return anything.

Coding Problems

Coding Problems - See the 'script' tag below this h3 tag. You will have to write some JavaScript code in it.

Always test your work! Check the console log to make sure there are no errors.