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 want to use functions in your code to organize better, avoid repetition, and make it easy read and maintain.
Question 2

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

The values that get passed into a function are called parameters (or 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 the block of code that defines what the function does. The characters that enclose the body of a function are 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)?

Calling or invoking a function means executing the function to perform its defined task. This is done by using the function's name followed by parentheses, optionally including arguments inside the parentheses.
Question 5

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

You use a comma (,) to separate multiple parameters in a function.
Question 6

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


function convertKilometersToMiles(km) {
    return km * 0.6217;
}
                

The problem with this code is that the function is missing curly braces { } around its body.
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 the value entered by the user, while the alert function does not return a value. This is why the first function call returns a value.

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.