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 type of code that is designed to perform a specific task.
Question 2

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

A value that gets passed within a function is called a parameter.
Question 3

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

The body of the function is the part of the code where it executes the task you design it to do. The body is often enclosed with curly braces {} after stating the function beforehand.
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 run the arguement that is passed into the function. This is often enclosed within braces () to call the function with the argument.
Question 5

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

You would use a comma to separate the parameters within a function.
Question 6

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


function convertKilometersToMiles(km)
    return km * 0.6217;
}
                

This line of code is missing the opening curly brace at the beginning of the body of the function.
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 function that returns a value is the line of code that prompts you to enter a name. This is so because unlike the 2nd line of code, the prompt function produces a result that an end-user inputs and stores it to be used elsewhere in the coding. The alert function only displays a message, but does not return any value - it does not give anything back to the code that it called.

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.