JavaScript Functions Worksheet

Question 1

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

Functions are reusable pieces of code that do a specific task. It helps reduce the amount of time spent writing 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.)

Yes all functions in JavaScript return a value.
Question 4

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 actual piece of code with instructions on what the function does. Curly Braces.
Question 5

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

It means to execute the function, telling the program to run the piece of code in the body.
Question 6

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

Just use a comma.
Question 7

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


function convertKilometersToMiles(km)
    return km * 0.6217;
}
                

The syntax error is that there is a curly brace missing after the parameter "km". It should look like this... function convertKilometersToMiles(km){ return km * 0.6217; }
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 + "!");
                

They both return a value because every function in JavaScript returns a value. The prompt function returns the name while the alert function takes that name and adds the Hello part.

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.