Back to Web Programming 1

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 line of code that you create early in the code and can call on later in the code. It saves you time due to only having to code the function once.
Question 2

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

The parameters and 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.)

Not all functions may return a value. If there is no value to be returned, or if the programmer forgets to include a return function.
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 contents within the curly braces({}). The curly braces enclose the body of the 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 program does whatever is within the function that is called. This is useful for if you want to use a function more than once, instead of writing it again you can just quickly call it.
Question 6

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

You would use a comma(,) to separate the parameters.
Question 7

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


function convertKilometersToMiles(km)
    return km * 0.6217;
}
                

First of all, a curly brace is missing after (km). Second of all, no value was given to km. Therefore the console will not give anything back for this.
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 first line would return a value due to name. When you open up the page there will be a prompt that asks for your name. And when you type in your name it returns with another pop up that says "Hello name!".

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.