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 recorded command of sorts that, once defined, can be recalled and used in the script as many times as necessary.
Question 2

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

Those are typically parameters, or just "params".
Question 3

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

The function's body is its definition. It's what exactly the function does upon being recalled, and it's enclosed in {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)?

It's programmer-speak for reusing a function. Whenever you have a function used after defining what it is, you're said to be invoking it.
Question 5

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

You'll use commas.
Question 6

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


function convertKilometersToMiles(km)
    return km * 0.6217;
}
                

The first curly brace ({) is missing. If left like this, the function will break upon being recalled. Also, assuming this is the only code, "km" has yet to be indentified.
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 + "!");
                

"alert()" is the command that returns a value, as the returned value is what gets shown to the user. "prompt()" takes a value in and stores it, but it doesn't output 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.