WordBlanks and Functions

The real lesson here is about passing values into a function.

You can declare a function the same way you declared variables:

function words(noun, adj, adv, verb)

In the snippet, above, we declared the name of a function (words), and we declared the names of four inputs for the function. You can think of it like a machine and we made four empty compartments on the assembly line. The first compartment is distinguished by the fact that it’s the first value in the parentheses, the second compartment is the second value in the parentheses, etc..

Then we add an opening curly bracket, just like we use in CSS. On the next line we tell our function what we want it to do with the inputs. In the FCC exercise, think of a sentence that would work with all four word types (an adjective, a noun, …) I chose a very simple sentence:

var result = "The " + myAdjective + " " + myNoun + " " + myVerb + " " + myAdverb + ".";

So, if we input the values cat, orange, crawls, playfully, then result would become The orange cat crawls playfully. We haven’t input anything yet, though, so, at this point, there are no values, no words, in the compartments. Think of the compartments as labeled boxes at this stage, but there is nothing in them. The machine (the function) can’t do anything yet because it’s boxes are empty.

While I do these exercises, I use a text editor so that I can see the output before it’s zapped away with a big, green checkmark. In the text editor, instead of return result, I use alert(result).

So, my text editor showed this, which works:

code from text editor that shows how to use functions for the Mad Libs Word Blanks exercise that will return a sentence made with an input noun, adjective, verb, and adverb

I named my variable “sentence” instead of “result”.

For the FCC exercise, keep the variable name “result”, and keep the third line and ending curly bracket as is. Then, in the last line, you can change the input values if you like, which is what will return different sentences. If you use a text editor and alert, you can see your sentences change with different inputs, and you’ll know that you understand the lesson.

Leave a Reply

Your email address will not be published. Required fields are marked *