How To Build a Mad Lib with JavaScript

Looking for a way to apply the basics of JavaScript?

Here's an easy way to practice concatenating strings and variables together in a function all while creating your first little program to play around with!

The first thing we need to do to make our mad lib is to set up our function so that we can concatenate the strings and variables together into the final sentence.

To do this we will first setup our function:

function madLib(noun, adjective){}

I named the function madLib and I created two variables called noun and adjective that we will use as arguments to pass through the function.

Next let's build the function by creating a variable called sentence that includes some given words as strings ( "I love my" and "because it is so" ) that we can add to the noun and adjective variables. I also added a return command so that when we run our program the computer will print the finished sentence.

function madLib(noun, adjective) {
    var sentence = "I love my " + noun + " because it is so " + adjective;
    return sentence;
  }

Now let's call our function with a console.log and include the name of the function and any noun and adjective we'd like to test. Notice the double sets of ( ) we need for the computer to understand what we are asking it to do, also notice that our variables are in " " so the computer see's it as text and not a variable:

console.log(madLib("pencil", "helpful"));

After running the function the computer will then print:

I love my pencil because it is so helpful

And that's it! Pretty simple! The mad lib can be as long as you want with any number of variables and strings as well and it's all because of the power of concatenating with functions!

You can check out an example of this function on my JsBin page.

Did you learn something new in JavaScript? Let me know what you thought by sharing your thoughts on LinkedIn or Twitter!

more from the blog

About Hailey
13 Acronymns Ever Aspiring Designer Should Know
5 Things You Didn't Know About Graphic Designers Before Computers