JavaScript Functions Worksheet

Question 1

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

Functions are lines or blocks of code that are designed to perform a task, which is also used to execute a group of statements multiple times without having to repeat the code.
Question 2

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

Arguments
Question 3

Do all functions return a value? (Note: this is a bit of a trick question - make sure to ask me about this in class.)

No, not all functions do. Some are used only to perform logging or modifying a varable without returning anything.
Question 4

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

This is the block of code that defines what the function does, and is enclosed within {}
Question 5

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

This means that you are executing the code in the function
Question 6

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

You use a comma to separate those parameters
Question 7

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


function convertKilometersToMiles(km)
    return km * 0.6217;
}
                

It's missing the opening curly brace, meaning it isn't properly defining the body of the function
Question 8

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 displays a dialog box that prompts the user to enter their name, while the alert function displays a message to the user but doesn't return 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.