No.6 Functions and Variables

Declaring Functions

In Lesson 5 we have seen JavaScript was written in the event handler on a HTML file.  In Exercise 05-10, the program/code (alert("Hello, world!");) was written inside the HTML file, thus a separate JavaScript file was not required.

However, as the program gets longer and longer it will be difficult to write all of the codes (many lines of codes) that way. Therefore, the program itself is usually written in a separate JavaScript file, and the event handler is used to call the program.

There are cases when one webpage uses multiple programs, therefore it is required to name each program.  A function is a bundle of program code/statements that can be called when needed. This way we can also give it a name.

Exercise 06-1(☆)
  1. Create  ex06-1.js and fill in the following.
  2. Create ex06-1.html in the same directory, fill in the following, copy them (HTML and JavaScript) to your public html as usual,  and access the html using the web browser.

Note that  this time “Hello, world!” did not pop out because it is not run/executed.  When a function { ... } is declared in the javascript , the  { ... } part is not executed, but it is only registered as a function so it can be called later on. In this Exercise, sayhello is the name of the function.  We will learn later why there are parenthesis written after the function name.

Registering a function like the exercise is called “declaring” a function.

Calling Functions

Once a function is declared, the program inside the function can be executed when we want by calling the function. It will be shown below.

Exercise 06-2(☆)
  1. Access the HTML file from the exercise 06-1 , open the console , type and run (pressing enter)  the following command on the console.
  2. Edit ex06-1.html and add the following inside the body element and reload the page. Note that here you are assigning/making this function as an event handler. The function will get executed/run when the “onclick” event happens (the button is being clicked)
  3. What happens when the line is changed to the following?

When we call a function, the program/code inside that function will be executed.

During the last lesson, we learned that we call the function Math.sqrt when calculating the square root of a number.  Math.sqrt and sayhello are both functions, but Math.sqrt is a function defined by the system (built-in function). sayhello is a function that you declared by yourself.


Exercise 06-3(☆☆☆)

Create a function saygoodbye, which shows the message “Goodbye.”, and create a button, which calls the function when it is clicked.


Variable Declaration

A variable is like a box that can contain data.  For instance, when we type innerHeight into the console, a number is displayed.  This is a variable used by the browser, which contains the value of the size of the window (technically the size of the content part).


We can make variables on our own. In order to do it, we execute the statement var variable_name;. This is called “declaring a variable”.

Exercise 06-4(☆)

Enter the following formulas in the web console and confirm the results.

  • x
  • var x;
  • x
  • When a name that hasn’t been declared as a variable or function is called, the Reference Error is returned.
  • When a variable that has no value is called, undefined is returned.(undefined is not an error)

Assigning a Value to a Variable

Saving data inside a variable is called assigning a value. We write variable = value; when assigning a value. If we want to declare a variable and its value together at once, we write var variable = value;.

Exercise 06-5(☆☆)
  1. Create ex06-5.js and fill in the following.
  2. Note the “+” sign inside the alert. It works exactly like it is for String data type (exercise 05-10)

  3. Create ex06-5.html and fill in the following.

  4. First of all, click on Greetings button.  Then click on Taro→Greetings→Hanako→Greetings.  What value is inside who and why?
  5. Edit ex06-5.js as the following and click in the same order as 3. Is there any difference?

These are the rules on where to declare variables.

  • A variable used by more than one function needs to be defined outside of the functions. (Generally written on the top of the JavaScript file). This is called a “global variable”
  • A variable used with only one function should be declared inside the function. This is called a “local variable”.
Exercise 06-6(☆☆☆☆)

When we click the button Taro and Hanako, there aren’t any actions /movements and you might be wondering.  Edit the file so that the message “Taro/Hanako has come” pops up when the button is clicked. Make a new function that displays “has come”, and call it from function taro() and hanako().

Function arguments

In the previous exercise, we made two different functions for taro and hanako. This wasn’t so difficult because there were only two people, but what if there were ten or hundreds?

An “argument” is used to process multiple data with one function.

  • When calling a function, the data or variable that we want to pass on is written inside the parentheses.
  • When declaring a function, we write a variable inside the parentheses. This variable will be assigned with the data used when the function is called.
Example 06-7(☆☆)
  1. Create ex06-7.js and fill in the following.
  2. Create ex06-7.html and fill in the following.
  3. What happens to variables x and who when Taro is clicked?
  4. Use function someone and make a button that greets “Rei”, “Shinji”, and “Asuka”.

When there are multiple arguments, each argument is separated by commas.

Manipulating HTML Elements using JavaScript (using innerHTML)

Unlike HMTL, which can display fixed/static text/information only, JavaScript can read and change what is displayed on the webpage by interacting (reading or changing/manipulating) with HTML elements. An HTML element can be accessed by JavaScript in 2 ways:

  1. reading it
  2. changing/manipulating it

In order to do it, we need to use the followings.

  • First,  in the HTML file, we mark the place (HTML element) which we want to access. There are a few ways to do it, but in this class we will be using theid attribute. This means we need to assign id attribute first to the HTML element that we want to read or change/manipulate using JavaScript.
  • Now that element has an id, we can refer to it  from JavaScript program by its id. We use the following statement (x is the id we assigned to the element):


For now, let’s look at the example where innerHTML is being used to read the “inner part” of an HTML tag (hence the name). The innerHTML basically refers to “whatever in between the tags”. Again as explained above we can use it in 2 ways:

  1. reading what (may already) exist in between the tags.
  2. changing/manipulating what (may already) exist between the tags. This will have an effect of, for example, changing/manipulating what is displayed on the web page, if it’s an HTML element that is related to displaying something on the page (text, image, etc).

For reading the format would be
z = document.getElementById(x).innerHTML

z will be assigned a value of whatever in between the tags of an HTML element with id=x

For changing/manipulating, the format would be document.getElementById(x).innerHTML = y

whatever in between the tag of an HTML element with id=x will be replaced by y

Note that z and y are String data type

Exercise 06-8(☆) Reading HTML element value using innerHTML
  1. Create ex06-8.js and fill in the following. Note that the JavaScript statements are referring to an HTML element with an id “who”.
  2. Create ex06-8.html and fill in the following. Which HTML element has id “who”? Its the paragraph <p> element! You can now see that the JavaScript above is”reading” a paragraph. In which way? It reads whatever in between the <p> and </p>. In this case its “world”. It then uses this value when displaying the alert/pop-up window
  • The id attribute and class attribute are similar, but in a HTML file, an id attribute with the same value cannot be used more than once.  In the case of the Exercise above, id=”who” is used in the p element, so in this HTML file, other elements cannot have the value id=”who”.
  • Elements with the id attribute can be accessed with JavaScript by using document.getElemetById().innerHTML.  This can be used like a variable (when reading), and when a new value is assigned (changing/manipulating) the display on the browser will change accordingly as well.

documentgetElementById() and innerHTML have the following meaning.

  • document : The source of the page displayed
  • getElementById() : A function which finds the specified ID(an HTML elements with a specified id)
  • innerHTML : The content with tags excluded.(“whatever in between the tags”)

Note that the 3 “keywords” above are joined together with a period/dot. In order to understand the meaning of the period, we must study “Objects”, but we will not go so far in this class.

Exercise 06-9(☆☆☆)Changing/manipulating HTML element value using innerHTML
  1. Take a picture of yourself with a different expression from the self introduction page using PhotoBooth, and save it in the same directory as the previous photo.
  2. Edit the img element on your self introduction page as the following: <div id="..."><img ...></div>
    • div element doesn’t have any functions by itself, but is used to add id and class attributes.
  3. Create ex06-9.js, and make a function that change/manipulate the content of the div element, to change the img element from the first photo to the second photo.
  4. Don’t forget to create  a <script> element/tag inside the <head> element which reads the JavaScript file we just made (ex06-9.js)
  5. Make a button (button #1, above or below the photo) that corresponds with the function that you made. (The onclick event on the button need to call that function)
  6. Open the file via browser and confirm that the photo changes when you click the button.
  7. Make another button(button #2) that returns the photo back to the original.

This is how it works: When you access the HTML by the web browser, the HTML gets loaded into the computer/web browser’s memory. The JavaScript change the HTML element inside the memory, but *not* the HTML file it self! (yes you can change the displayed photo by changing the HTML, save it and reload the HTML again as well, but this is static, not dynamic. With JavaScript above you can change the displayed photo by clicking a button!

Try opening a web page, then open Google Chrome’s Developer Tools (View-Developer-Developer Tools), “Elements” tab. Try changing some elements, you will see the result will be reflected straight away. This is because you are changing the memory content , *not* the html source file itself!

Executing a Function with a Timer Event

By using a Timer event, we can execute functions after a certain period of time or evert a certain period.

Exercise 06-10(☆)
  • Execute the following command via console.

The setTimeout function has the following two arguments

  • A string that contains a program you want to execute.
  • How many milliseconds (1 second is 1000 milliseconds) before it gets executed.

Double quotes are used in the Exercise above to distinguish them from the single quotes outside alert().

Exercise 06-11(☆☆☆☆☆)

Modify Exercise 06-9 so that the photo automatically switch back 5 seconds after you click the button #1. Keep button #2

Points to check
  • What is a function?
  • How do you declare a function?
  • What is a variable?
  • How do you declare a variable?
  • How do you assign a value to a variable?
  • What happens when you use arguments?
  • What is the id attribute used for?