JavaScript Functions Worksheet

Question 1

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

A function in programming is a reusable block of code that performs a specific task. It allows you to group a set of instructions together so that you can execute them by calling the function whenever needed, rather than writing the same code multiple times.
Question 2

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

Arguments or parameters.
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 contains the statements that perform the work, such as printing output, performing calculations, or modifying data.
Question 4

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

When you call a function, you are essentially asking the program to run the code inside that function to perform the task defined within it.
Question 5

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

A comma ",".
Question 6

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


function convertKilometersToMiles(km)
    return km * 0.6217;
}
                

It's missing the "{". With out it the program doesn't know where to start or end 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 "Prompt" function returns the value. Its a display asking for the user to input some text.

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.