Lessons menu
JavaScript - advanced - Lesson nr. 3
JavaScript variables and parameters to functions

What this lesson is about?
In this lesson we will learn about variables, a way to temporarily store data until it gets handled. We learn about parameters, the way functions can communicate. These two new features help us to create more complicated and general functions, to be more elegant in coding. We will talk about data types and some operations related to variables.

New objects in this lesson:
Date – this object is used to define the date type used in JavaScript. With the objects of this type we can find out the current date and time, we can create date from other data and use the methods associated with this type.
Math – this object contains all the mathematical methods which are available in JavaScript. So if you need to calculate absolute value, square root or round a number etc.

New methods in this lesson:
clearTimeout(reference to a timer) – this method of the window object is used to stop a timer set by a setTimeout method. 
getHours – we can extract the hour from an object with the date type. The result is a number between 0 and 23.
getMinutes – we can extract the minutes from an object with the date type. The result is a number between 0 and 59.
getSeconds – we can extract the seconds from an object with the date type. The result is a number between 0 and 59.  
Math.floor(number) – this method rounds the number added as parameter to the nearest integer downward and returns the value.
Math.random() – this method returns a random float number between 0 and 1.

What are variables?
When writing a longer code we may need to store data to use later. We can achieve this, by adding a name to the data. The named data we call variable, because its value can be altered and reused multiple times.

The simplest statement related to variables is the assignment. Using an equal sign we can assign a value to a variable or data field of an object. The assigned value can be the result of an expression, the value of another variable or an object’s data field.

The type of that data is important. JavaScript variables do not require stating the type, but after it gets a value, it is important to know what the type is.

The most common types of data we use, are number and text (string). They behave differently when subjected to operators and added to statements so we need to understand their behavior.

Example on numbers:

In the example above we can see 4 variables: x, y, z and v.

When we use a variable, we write the keyword var before it.

The x gets an integer as value, the number 5. The y variable gets a real number as value: 0.5.

The contents accessed from the HTML documents are texts, if we want to use them as numbers we need to convert them. The Number() method is one of the possibilities to do that.

The values of the v and z variables are the ones written in the two paragraphs of the HTML document.

Using addition between two numbers executes the mathematical addition we expect, and adding the resulting numbers back to the paragraphs, needs no explicit conversion to text, it will be solved automatically.

Example on strings:

In the example above we have the fn and ln variables, they get their string type values at once. Concrete texts in a code are wrapped in quotation marks. To strings we have a few methods attached, one of them is the length method, used to find out the length of a string.

In the l variable we add a number. In the name variable we concatenate the two strings and one space between them. Both the number and the text can be added to the content of the webpage.

The second function has a += operation, this means that we add the + symbol at the end of the existing text in the HTML tag. Until now we have always overwritten the content.

Guidance – data types:
If a JavaScript expression does not result in a type you expected, you should examine the types in the expression, the succession of the elements and try to force data transformation (like Number or toString methods)

Text and number are basic data types you find in every programming language. But we can create more complicated types combined with methods, called JavaScript objects. In JavaScript every HTML element becomes an object and we saw previously the window and document objects.

Example on date:

In the example above, we have the tick function, which starts for the first time when loading the page, and then it schedules itself to be recalled after 1 second.

There is a reference to the timer in the t variable, so the stop function can stop it when needed. Otherwise the “loop” of starting over is infinite.

The t variable is a reference to an object, and so is the d variable. In the case of t variable we save the value the setTimeout function returns, for the d variable we create a brand new object with date type. This way we capture a moment in time in the d variable (having a year, a month, a day, an hour, a minute and second combined in it). We can get these values out of it by using methods: getHours(), getMinutes(), getSeconds() in this example.

What are parameters?

Exchanging data between two functions or a function and the pages’ content happens through parameters – they can be called special variables.

Using parameters we can solve problems more generally: we can define data we necessarily needed to solve the task assigned to the function and call the function from different places, and with different values.

Example on function with parameters:

In this example we have one function named change with two parameters (a, b). The first one refers to an HTML object (which has an innerHTML property), the second one is a text that will be added to webpage.

The function is called when one of the buttons is clicked on. The text is different every time and the HTML object too. We can use this reference – we do not need to add id-s to find the right button later. The code is definitely shorter.

Example on function returning value:

In the example above, we have 2 new functions: randnum and randcolor. Both of them have the return a statement. These functions do not add their result to the webpage’s content directly. Their result is a number, respectively a string and the result is given back by the return and placed to the statement where the function calling takes place.

The randnum function converts the float number given by the Math.random method to an integer below the a number. The result is returned and placed in the statement numb=randnum(255) and the other two. There will be three different values returned for the three different callings.

The randcolor builds a string defining a color in RGB form, with three different numbers below 255. The result from the c variable is returned and placed in the change function. This way the color gets applied as background color to the button.

When naming functions be aware that there cannot be two functions with the same name and number of parameters in one scope (in one webpages “sight”, in the list of functions which can be called inside the page and in the js files listed).

1. Change the forms.html file: at the beginning of the page, after the “clock” we made before, The time you arrived, followed by the hour, minute and second when you opened the page, then write under it Time spent on the page, followed by a counter in seconds. Put all these in a div section and give it the same design as the “clock” has.
View the result
2. Change the index.html file: we added previously JavaScript code to every image in the gallery, so they disappear when we click them. Create a function to do the same.
View the result
3. Change the index.html file:
Add three boxes below the gallery, containing one quotation each, one about work, one about friends and one about time.

You can use the ones below:
A dream doesn't become reality through magic; it takes sweat, determination and hard work.
Share your smile with the world. It's a symbol of friendship and peace.
Time you enjoy wasting is not wasted time.

Add three buttons with the texts (Work, Friends and Harmony). They should not have a border to merge with the box below.
Choose a separate color for every quotation, the button and the box should be the same color.
There should be only one quotation visible at once – the one of which buttons we pressed the last time. The first should be shown by default.
The default formatting should be set in the CSS file, use a function called show when clicking on one of the buttons. The function should get as parameter the id of the box to be shown.

View the result
4. Change the gallery.html file:
Add a new section below the gallery containing a button with the text Random picture and the first image form the gallery.
Using functions the page should show a different one from the 8 pictures we have in the gallery folder, every time we hit the button. Use a separate function to generate the name of the picture to be displayed, knowing that their names are numbers: 01.jpg, 02.jpg, … 08.jpg.
View the result
1. The variable b defined as var b=document.getElementById("x").innerHTML contains data of the type:
2. What will appear on the page in the element identified as x after executing the function below?

function something() {
var s= "10";
var z= "5";
z=z + s + z;

3. Which of the following Date methods is inexistent?
4. Examine the function below. What type is the x parameter?

function something(x, y) {

5. What will be the result of the Math.floor(1.75) expression?
6. What can be the result of the Math.random()*10 expression?
7. What could be the result of the following code?

<img src="pic.jpg" alt="Missing picture" onclick="change(this)"/>
function image() {
             var d=new Date();
             var name=d.getHours();
             return name;
function change(x){

Exclamation mark This site is using cookies. By continuing to browse the site, you accept their use! I accept