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 reusable block of code that performs a specific task. You use functions to avoid repeating code, to organize your program into logical sections, and to make your code easier to maintain and debug.
Question 2

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

The values passed into a function are called arguments, and they are received by parameters inside the function.
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 the set of statements that define what the function does. It is enclosed within curly braces { }.
Question 4

What does it mean to 'call', or 'invoke' a function?

To call or invoke a function means to execute the code inside it. You do this by writing the function’s name followed by parentheses, optionally with arguments inside them.
Question 5

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

Parameters are separated by a comma (,).
Question 6

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


function convertKilometersToMiles(km)
    return km * 0.6217;
}
                

The function is missing an opening curly brace { after the parameter list. The correct syntax should be:
function convertKilometersToMiles(km) {
    return km * 0.6217;
}
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 — specifically, the text that the user enters. The alert() function does not return anything; it only displays a message to the user.

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.