Tap for Menu

Variables & Functions

Variables and Functions make JavaScript very powerful. Start with your barebones HTML document and then let's go into the script tags. Check out the code snipped below. It will be confusing, but that's okay!

I start out by declaring two variables. The Variable Name is "firstname" and "lastname". I then give a Value to these variables. Variables can be several things like numbers, strings or boolean. (True/False). Since I didn't declare these variables inside a function, they are known as Global and can be used by any function. If you would like to use a variable in only one function it is known as Local.

After declaring the variables I am going to be using, I start with my first function! The name of the function is "showname". Different Arguments can be place inside the parenthesis. After defining the name I open what the function does with the "{" character. In this case I have it show an alert of two variables. It refrences my firstname variable, then a string of text for a space, and finally my last nmae. Make sure to end it with a semi colon and then close the function with another "}".

If I wanted to call this funciton on load I just list the function in the script tag. If I want to call it on a certian event, like a button press, I use the HTML "onclick" argument. In this example I sipmly created a button to do this. You can also use this right in the body tag!

Adding Interactivity

Let's make a simple document that asks the user for their name, then tells them hello!

Start with a regular HTML document but then also add a [p] tag. Give it an id of "para". This allows us to access this paragraph using JS.

First we start by creating a new function called "getname". Inside the function we add a new variable called "name" which we then prompt the user for. Whatever they enter will be the variable. This is a Local variable because it is inside a function.

Now we are going to get the ID of the paragraph tag we made earlier and change it's HTML content to add some things. You can see that we add "Hello " + the "name" variable.

Add one more button, and try it out for yourself!