4. JavaScript

4.1. Introduction

  • JavaScript is a dynamic language which is used for designing the web pages on the client side.
  • It is case sensitive language.
  • It is untyped language i.e. a variable can hold any type of value.
  • // is used for comments.
  • ; i used for line termination.
  • JavaScript code should be added at the end i.e. just above the closing-body-tag.
  • It is better to write the JavaScript code in separate file as shown in next section.

4.2. First code

The JavaScript code can be written in the ‘html’ file or in the separate ‘JavaScript file (.js)’ as shown in this section,

4.2.1. JavaScript in HTML file

In HTML file, the JavaScript codes can be written inside the ‘script’ tag as shown in Lines 11-13 of below code. The code will write the message “Hello World from JavaScript!” on the web page. Open the ‘js.html’ in the browser to see the message.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
<!-- js.html -->

<!DOCTYPE html>
<html>
<head>
    <title>JavaScript</title>
</head>
<body>


    <script type="text/javascript">
        document.write("Hello World from JavaScript!<br>");
    </script>

</body>
</html>
  • Below is the output on the HTML page,
Hello World from JavaScript!

4.2.1.1. JavaScript in separate file

  • The JavaScript code is saved in the file ‘my_javascript.js’ which is located inside the folders ‘asset/js’. Note that, no ‘script tag’ is used here.
1
2
3
// asset/js/my_javascript.js

document.write("Hello World from JavaScript!<br>");
  • Next we need to import the .js file in the HTML file as shown below,
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
<!-- js.html -->

<!DOCTYPE html>
<html>
<head>
    <title>JavaScript</title>
</head>
<body>



    <!-- import JavaScript files here -->
    <script src="asset/js/my_javascript.js"></script>

</body>
</html>
  • Now, open the ‘js.html’ file in the browser and it will display the message.

Note

We will use the second method in this tutorial.

4.3. Keywords, Datatypes, Variables and Operators

4.3.1. Keywords

  • Below are the reserved keywords in the JavaScript which can not be used as ‘variable’ and ‘function’ names etc.
Table 4.1 List of keywords
Keywords      
abstract boolean break byte
case catch char class
const continue debugger default
delete do double else
enum export extends false
final float for function
goto if implements import
in int interface long
native new null package
private protected public return
short static super switch
this throw throws transient
true try typeof var
void volatile while with

4.3.2. Datatypes

JavaScript has three types of data,

  • Numbers : 123, 32.32
  • Strings : “Meher”, “Krishna Patel”, “123”
  • Boolean : true, false

Note

All the numbers are considered as ‘floating point’.

4.3.3. Variables

Variables can be define using keyword ‘var’. Further, JavaScript is untyped language i.e. a variable can hold any type of value.

  • In the below HTML, ‘p’ tag with id ‘p_name’ is defined at Line 10. This id will be used to write some text using JavaScript,
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
<!-- js.html -->

<!DOCTYPE html>
<html>
<head>
    <title>JavaScript</title>
</head>
<body>

    <p id='p_name'></p>

    <!-- import JavaScript files here -->
    <script src="asset/js/my_javascript.js"></script>

</body>
</html>
  • Two variables are defined at Lines 9-10 of type ‘string’ and ‘float’ respectively. Then ‘getElementById’ is used to locate the tag with id ‘p_name’ and the text is inserted as shown in Line 11. Lastly, the ‘+’ sign is used to concatenate the values as Line 11.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
// asset/js/my_javascript


// print message on the webpage
document.write("Hello World from JavaScript!<br>");


// variable example
var your_name = "Meher";
var age = 20;
document.getElementById("p_name").innerHTML= "Hello "+ your_name + "<br>Age : " + age;
  • Below is the output of above codes. Note that the message ‘Hello World from JavaScript!’ is added at the end as ‘JavaScript’ file is imported at the end.

Warning

If we import the ‘JavaScript’ file between the ‘ending-head-tag’ and ‘start-body-tag’, then Message ‘Hello Meher …’ will not be displayed as ‘JavaScript’ will execute before the loading of the page; and JavaScript can not find the id ‘p_name’.

Hello Meher
Age : 20

Hello World from JavaScript!

Note

All the JavaScript/HTML codes will be added below the existing codes, therefore only the newly added code will be shown in the rest of the tutorial.

  • ‘prompt’ can be used to read the values from the user.
// prompt
var x = prompt("enter a number");
document.write("2 * ", x, " = ", 2*x + "<br>");

A pop-up window will appear due to prompt. If we provide the input value as 3, then below output will be generated,

2 * 3 = 6

Note

The ‘,’ and ‘+’ can be used to combine various outputs as shown in above example

4.3.4. Operators

Various operators are shown in this section. The usage of some of these operators are shown in Section 4.4.

4.3.4.1. Arithmetic operators

  • +
  • -
  • *
  • /
  • % : modulus i.e remainder of the division
  • ++ (increment)
  • – (decrement)

4.3.4.2. Assignment operators

  • =
  • +=
  • -=
  • *=
  • /=
  • %=

4.3.4.3. Comparison operators

  • == (compare only values not type)
  • === (compare both values and type)
  • !=
  • >
  • <
  • >=
  • <=

4.3.4.4. Conditional operator

  • ?:

e.g. ‘( (a > b) ? a/b : b/a) )’ i.e if ‘a>b’ then do ‘a/b’ else do ‘b/a

4.3.4.5. Logical operators

  • && (logical and)
  • || (logical or)
  • ! (logical not)

4.3.4.6. Bitwise operators

  • & (and)
  • | (or)
  • ^ (xor)
  • ~ (not)

4.3.5. String to number conversion

‘Number’ is used to convert the string into numbers.

// string to number conversion
document.write("2 +  Number('3.4') = ", 2 + Number('3.4'), "<br>");

Below is the output of above code,

2 + Number('3.4') = 5.4

4.3.6. Convert to integer

A string or float value can be converted into integer using ‘parseInt’

// int conversion
document.write("2 + parseInt('3.4') = ", 2 + parseInt('3.4'), "<br>"); // string to int
document.write("2 + parseInt(3.4) = ", 2 + parseInt(3.4), "<br>"); // float to int

Below are the outputs of above code,

2 + parseInt('3.4') = 5
2 + parseInt(3.4) = 5

4.3.7. Convert to float

The ‘parseFloat’ or ‘Number’ can be used to convert the value into float values.

document.write("2 + parseFloat('3.4') = ", 2 + parseFloat("3.4"), "<br>"); // parseFloat

4.3.8. Math

‘Math’ library contains various useful function as shown below,

// math
document.write("pi =  ", Math.PI, "<br>");
document.write("e =  ", Math.E, "<br>");
document.write("similarly we can use 'abs', 'floor', 'ceil' and 'round' etc. <br>")
document.write("random number : ", Math.ceil(Math.random()*20), "<br>"); // enter random number

Below are the ouputs of above code,

pi = 3.141592653589793
e = 2.718281828459045
similarly we can use 'abs', 'floor', 'ceil' and 'round' etc.
random number : 16

4.3.9. String

Below are the some of the useful ‘string-styles’,

// string
document.write("meher".toUpperCase(), "<br>")  // uppercase

w = "Krishna"
document.write(w.toLowerCase(), "<br>")  // lowercase
document.write(w.small(), "<br>")  // small
document.write(w.bold(), "<br>")  // bold
document.write(w.strike(), "<br>")  // strike
document.write(w.fontsize("5em"), "<br>")  // strike
document.write(w.link("http://pythondsp.readthedocs.io"), "<br>")  // link

document.write(w.fontcolor("red").fontsize("12em"), "<br>")  // multiple

The outputs are shown in Fig. 4.1

../_images/javascript1.png

Fig. 4.1 String styles

4.3.10. Arrays

In JavaScript, the arrays can store different types of values as shown in below code,

// arrays
arr = [15, 30, "Meher"]
for(a in arr)
    document.write(arr[a], " ");
document.write("<br>");

document.write(arr.pop(), "<br>");  // remove last element
arr.push("Krishna"); // add element to end
document.write(arr.pop(), "<br>");
document.write("lenght of array: ", arr.length, "<br>");

Below are the output of above code,

15 30 Meher
Meher
Krishna
lenght of array: 2

4.4. Control structure, loops and functions

4.4.1. If-else

In the below code, three conditions are checked for the variable ‘age’; and corresponding message is printed.

// asset/js/my_javascript

// if-else
age = 10;
if (age > 3 && age < 6){
    document.write("Age : " + age + "<b> go to kindergarten</b>");
}
else if ( age >=6 && age < 18){
    document.write("Age : " + age + "<b> go to school</b>");
}
else{
    document.write("Age : " + age + "<b> go to college</b>");
}
document.write("<br>");
  • Since age is 10, therefore ‘else if’ statement is satisfied and we will get below output,
Age : 10 go to school

4.4.2. Switch-case-default

Below is an example of Switch-case-default statement,

// asset/js/my_javascript

// switch-case
var grade = 'A';
document.write("Grade " + grade + " : ");
switch(grade){
    case 'A':
        document.write("Very good grade!");
        break;
    case 'B':
        document.write("Good grade!");
        break;
    default: // if grade is neither 'A' nor 'B'
        document.write("Enter correct grade");
}
document.write("<br>");
  • Below is the output of above code,
Grade A : Very good grade!

4.4.3. For loop

Below code prints the value from 5-0,

// For loop
for (i=5; i>=0; i--){
    document.write(i + " ");
}
document.write("<br>");
  • Below is the output,
5 4 3 2 1 0

4.4.4. While loop

Below code prints the value from 0-4,

// While loop
x=0;
while(x < 5){
    document.write(x + " ");
    x++;
}
document.write("<br>");

4.4.5. do-while

Below code prints the value from 0-2,

// do-while
x=0;
do{
    document.write(x + " ");
    x++;
}while(x < 3);
document.write("<br>");

Below is the output,

0 1 2

4.4.6. for-in loop

The ‘for-in’ loop can be used to iterate over the array as shown below,

// for-in loop
arr = [10, 12, 31];  // array
for (a in arr){
    document.write(arr[a] + " ");
}
document.write("<br>");

4.4.7. Continue and break

Continue and break statements are used inside the ‘loop’ statements.

  • Continue will skip the loop and go to next iteration, if the condition is met. In the below code, 3 will not be printed at the output.
// continue
for (i=5; i>=0; i--){
    if (i==3){  // skip 3
        continue;
    }
    document.write(i + " ");
}
document.write("<br>");

Below is the output where 3 is not printed in the output.

5 4 2 1 0
  • ‘Break’ statement will quit the loop if the condition is met. In the below code, the for loop will be terminated at ‘i=3’, therefore only 5 and 4 will be printed,
// break
for (i=5; i>=0; i--){
    if (i==3){ // exit loop when i=3
        break;
    }
    document.write(i + " ");
}
document.write("<br>");

Below is the output of the above code,

5 4

4.4.8. Functions

In the below code a function ‘add2Num’ is defined which adds the two numbers and returns the result.

// function
function add2Num(num1, num2){ // function definition
    return num1 + num2;
}
sum = add2Num(2, 3); // function call
document.write("2 + 3 = " + sum);
document.write("<br>");

Below is the output,

2 + 3 = 5

4.5. Event handling

One of the main usage of JavaScript is ‘event handling’. “Mouse click” and ‘pressing keys on keyboard’ are the example of ‘events’. With the help of JavaScript, we can perform certain actions at the occurrence of the events, as shown below.

  • ‘alert’ is used to display message in the ‘pop up’ window.
function alertMessage(message){
    alert(message)
}
  • In Line 13, message ‘Hello’ is shown in the pop-up window on the event ‘onclick’. Note that “JavaScript:void(0)” is used here, which does not refresh the page.
  • Line 15 is same as Line 13, but “JavaScript:void(0)” is not used, therefore page will be refreshed.
  • Line 17 calls the function ‘alertMessage’ to display the mesage, which is defined in the above code.
  • Lines 19-25 use different events i.e. ‘onmouseover’, ‘onmouseleave’, ‘onmouseup’ and ‘onmousedown’; and the color and the text of the string changes based on these operations.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<!-- js.html -->

<!DOCTYPE html>
<html>
<head>
    <title>JavaScript</title>
</head>
<body>

    <p id='p_name'></p>


    <a href="JavaScript:void(0)", onclick="alert('Hello')">Say Hello</a><br> <!-- do not reload the page -->

    <a href="", onclick="alert('Hello')">Say Bye</a><br> <!-- reload the page -->

    <a href="JavaScript:void(0)", onclick="alertMessage('Bye via function')">Bye-function</a><br>

    <a href="JavaScript:void(0)",
        onmouseover="this.style.color='red'",
        onmouseleave="this.style.color='blue'",
        onmouseup="this.text='Not clicked'",
        onmousedown="this.text='You clicked me'">
        Not clicked
    </a><br>


    <!-- import JavaScript files here -->
    <script src="asset/js/my_javascript.js"></script>

</body>
</html>

4.6. Conclusion

In this tutorial, we have selected the element with certain ‘id’ using ‘getElementById’. Also, we saw the example of ‘event handling’ Although, we can use JavaScript for these operations, but it is better to use jQuery for these purposes, which is discussed in Chapter 5. A good approach is use to the jQuery for ‘selectors’ & ‘event handling’ and then use various features of JavaScript which are described in Section 4.4 to implement the logics.