JavaScript Functions Worksheet

Question 1

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

Funtions are a group of statements. You would use functions if you are going to repeat the same lines of code throughout the program so you don't need to retype or copy/paste the same code over and over.
Question 2

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

Parameters.
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. Return initializes a variable. Not all functions will do this.
Question 4

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

The statements to be executed when the function is called. { } are the characters that enclose the body of a function.
Question 5

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

The simplest way to explain is that it means use.

When you create a function it doesn't run itself. You have to call/invoke it elsewhere to have it run.
Question 6

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

, (comma)
Question 7

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


function convertKilometersToMiles(km)
    return km * 0.6217;
}
                

The { is missing after the (km) so the opening syntax to indicate the body is missing.
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 + "!");
                

prompt is the function that returns a value. prompt is initializing a variable.

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.