JavaScript Functions Worksheet
Question 1
What is a function, and why would you ever want to use one in your code?
Functions are a fundamental programming concept used is all programming lanuages.
Functions are important to use in our code because it allows us to execute a group of statements multiple times in our program without having to repeat code.
Question 2
What do you call the values that get passed into a function?
The value we put into a function is called a parameter.
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.)
If return is not explicitly used the value returned will be Undefined.
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 a block of code that is executed when a function is invoked/called, the body is enclosed by 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)?
To 'invoke' a function is to execute the code that is defined within in the function. In order to 'call' a function in our code we type the funcion name followed by a pair of parenthesis
and we need to end the statement with a semicolon ;.
Question 6
If a function has more than one parameter, what character do you use to separate those parameters?
We can use a comma ',' to separate multiple parameters in a function.
Question 7
What is the problem with this code (explain the syntax error)?
function convertKilometersToMiles(km)
return km * 0.6217;
}
There is no opening curly bracket '{'.
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 fuction that includes prompt is the one that returns a variable, we know this is the case because of the variable in the same line of code name.
Name in this code stores what ever gets returned by prompt.
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.