002 – Functions and Variables – JavaScript Noob to Pro Tutorials

In the last episode, we had a button that would change the contents of a div on click. However, we put all of our code into the HTML element. This doesn’t make the code particularly easy to read and it also means that things will get messy if we need to do more with the button than just modify the contents of the div.

In the last episode we had this code:


In order to extract the code from the button click, we can stick it somewhere else and reference it where we would have normally executed the code. Think of this like using CSS to modify a class or ID.

So what we can see here is that we have added “function buttonClicked(){}” inside our “script” tags. Then inside the curly braces “{}”, we have added the code that was previously in the “onClick” method.

Then inside the “onClick” method on the button, we have referenced the function by calling “buttonClicked()”. We will cover what the purpose of the “()” is later in this episode.

This is starting to look much cleaner now and if you go ahead and click your button then you will see it performs the same action as before.


Let’s take this a step further and add variables to our code. A variable again works a bit like a CSS selector. You assign a value to it then reference it where it’s needed.

There are a few ways to declare a variable in JavaScript. For now though we will use “var”.

So here we have added a variable called “text”. You can call your variable whatever you like. Then we have called our variable where we would normally have put our string by just typing the name of the variable.

Passing data to the function

To combine the two things we just learned, we can pass our string to the function from the button click. This is where the “()” comes into play.

Where we have called the function on button click we can add our string like this “buttonClicked(‘Hello World!’)”. Then on the function declaration in the script tags, we can assign the string that is passed through to a variable by just declaring “function buttonClicked(text)”.

What this allows us to do is call the function from more than one place and pass it a different string. So for example, if we had a second button where we wanted to display something else on click, then we can call the function the same way we did before but with different text.

As you can see, clicking the second button displays “I am different!”.

In the next episode we will be looking to use JavaScript in a real-world situation. We will be validating a form and exploring data types in the process.

You may also like...

Leave a Reply

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