Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
19 views

Module 08 Intro JS

Uploaded by

Vincent Siaron
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Module 08 Intro JS

Uploaded by

Vincent Siaron
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 29

FM-AA-CIA-15 Rev.

0 10-July-2020

Study Guide in WD101 Web Development Module No. 8

STUDY GUIDE FOR MODULE NO. 8

Introduction to JavaScript
MODULE OVERVIEW

This module covers all the fundamentals of JavaScript including the idea of JavaScript,
embedding JS, syntax, variables and data types, conditional and looping statement, arrays,
functions and event handling.

MODULE LEARNING OBJECTIVES

At the end of this module, students are expected to:

1. Understand what is JavaScript?


2. Understand and demonstrate the three ways of adding JavaScript to a web page
a. Embedded JavaScript
b. External JavaScript
c. Inline JavaScript
3. Understand JavaScript Syntax
4. Understand the use of Variables and Data Types
5. Understand and demonstrate conditional and looping statements using JavaScript
6. Understand and demonstrate the use of Arrays in JavaScript
7. Understand and demonstrate the use of Functions in JavaScript
8. Understand and demonstrate the use of Event Handling in JavaScript

LEARNING CONTENTS (Introduction to JavaScript)

What is JavaScript?

 JavaScript was initially created to “make web pages alive”.


 The programs in this language are called scripts. They can be written right in a web
page’s HTML and run automatically as the page loads.
 Scripts are provided and executed as plain text. They don’t need special preparation or
compilation to run.

History of JavaScript

 JavaScript was originally developed as LiveScript by Netscape in the mid-1990s.


 It was later renamed to JavaScript in 1995, and became an ECMA standard in 1997.
 JavaScript is officially maintained by ECMA (European Computer Manufacturers
Association) as ECMAScript. ECMAScript 6 (or ES6) is the latest major version of the
ECMAScript standard.

What can you do with JavaScript?

 There are lot more things you can do with JavaScript such as:
 You can modify the content of a web page by adding or removing elements.
 You can change the style and position of the elements on a web page.
 You can monitor events like mouse click, hover, etc. and react to it.
 You can perform and control transitions and animations.
 You can create alert pop-ups to display info or warning messages to the user.
 You can perform operations based on user inputs and display the results.
 You can validate user inputs before submitting it to the server.

PANGASINAN STATE UNIVERSITY 1


FM-AA-CIA-15 Rev. 0 10-July-2020

Study Guide in WD101 Web Development Module No. 8

CTIVITY 1

LEARNING CONTENTS (Three ways to add JavaScript to a web page)

There are typically three ways to add JavaScript to a web page:

 Embedding the JavaScript code between a pair of <script> and </script> tag.
 Creating an external JavaScript file with the .js extension and then load it within the
page through the src attribute of the <script> tag.
 Placing the JavaScript code directly inside an HTML tag using the special tag attributes
such as onclick, onmouseover, onkeypress, onload, etc.

Embedding the JavaScript Code

 You can embed the JavaScript code directly within your web pages by placing it between
the <script> and </script> tags. The <script> tag indicates the browser that the
contained statements are to be interpreted as executable script and not HTML.

Example: Create an HTML file named “embeddedjs.html” and place the following code in it:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Embedding JavaScript</title>
</head>
<body>
<script>
var greet = "Hello World!";
document.write(greet); // Prints: Hello World!
</script>
</body>
</html>

Calling an External JavaScript File

 You can also place your JavaScript code into a separate file with a .js extension, and
then call that file in your document through the src attribute of the <script> tag, like
this:
 <script src="js/hello.js"></script>
 This is useful if you want the same scripts available to multiple documents. It saves you
from repeating the same task over and over again, and makes your website much easier
to maintain.

Example: Create a JavaScript file named “hello.js” and place the following code in it:

// A function to display a message


function sayHello() {
alert("Hello World!");
}
// Call function on click of the button
document.getElementById("myBtn").onclick = sayHello;

 Create an HTML file named “extenaljs.html” and place the following code in it:

<!DOCTYPE html>

PANGASINAN STATE UNIVERSITY 2


FM-AA-CIA-15 Rev. 0 10-July-2020

Study Guide in WD101 Web Development Module No. 8

<html lang="en">
<head>
<meta charset="UTF-8">
<title>Including External JavaScript File</title>
</head>
<body>
<button type="button" id="myBtn">Click Me</button>
<script src="hello.js"></script>
</body>
</html>

Placing the JavaScript Code Inline

 You can also place JavaScript code inline by inserting it directly inside the HTML tag
using the special tag attributes such as onclick, onmouseover, onkeypress, onload, etc.
 However, you should avoid placing large amount of JavaScript code inline as it clutters
up your HTML with JavaScript and makes your JavaScript code difficult to maintain.

Example: Create an HTML file named “inlineljs.html” and place the following code in it:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Inlining JavaScript</title>
</head>
<body>
<button onclick="alert('Hello World!')">Click Me</button>
</body>
</html>

LEARNING ACTIVITY 1

Create a page that shows a message “I’m JavaScript!” using the three ways of adding a
JavaScript to a web page.

LEARNING CONTENTS (Understanding JavaScript Syntax)

JavaScript Syntax

 The syntax of JavaScript is the set of rules that define a correctly structured JavaScript
program.

 A JavaScript consists of JavaScript statements that are placed within the


<script></script> HTML tags in a web page, or within the external JavaScript file having
.js extension.

Example:

var x = 5;
var y = 10;
var sum = x + y;
document.write(sum); // Prints variable value

Case Sensitivity in JavaScript

PANGASINAN STATE UNIVERSITY 3


FM-AA-CIA-15 Rev. 0 10-July-2020

Study Guide in WD101 Web Development Module No. 8

 JavaScript is case-sensitive. This means that variables, language keywords, function


names, and other identifiers must always be typed with a consistent capitalization of
letters.
 For example, the variable myVar must be typed myVar not MyVar or myvar. Similarly,
the method name getElementById() must be typed with the exact case not as
getElementByID().

JavaScript Comments

 JavaScript support single-line as well as multi-line comments. Single-line comments


begin with a double forward slash (//), followed by the comment text. Here's an
example:

Example:

// This is my first JavaScript program


document.write("Hello World!");

/* This is my first program


in JavaScript */
document.write("Hello World!");

LEARNING CONTENTS (JavaScript Variables and Data Types)

JavaScript Variables

 Most of the time, a JavaScript application needs to work with information. Here are two
examples:
 An online shop – the information might include goods being sold and a shopping cart.
 A chat application – the information might include users, messages, and much more.
 A variable is a “named storage” for data. We can use variables to store goodies, visitors,
and other data.

What is Variable?

 To create a variable in JavaScript, use the var keyword.


 The statement below creates (in other words: declares) a variable with the name
“message”:

var message;

 Now, we can put some data into it by using the assignment operator =:

var message;

message = 'Hello'; // store the string

 The string is now saved into the memory area associated with the variable. We can
access it using the variable name:

var message;
message = 'Hello!';

PANGASINAN STATE UNIVERSITY 4


FM-AA-CIA-15 Rev. 0 10-July-2020

Study Guide in WD101 Web Development Module No. 8

alert(message); // shows the variable content

 To be concise, we can combine the variable declaration and assignment into a single
line:

var message = 'Hello!'; // define the variable and assign the value

alert(message); // Hello!

 We can also declare multiple variables in one line but a multiline declaration is more
easier to read:

var user = 'John', age = 25, message = 'Hello';

var user = 'John';


var age = 25;
var message = 'Hello';

 A variable should be declared only once.


 A repeated declaration of the same variable is an error:

var message = "This";

// repeated 'var' leads to an error

var message = "That"; // SyntaxError: 'message' has already been declared

JavaScript Data Types

 Data types basically specify what kind of data can be stored and manipulated within a
program.
 There are six basic data types in JavaScript which can be divided into three main
categories:
o Primitive (or primary)
 String
 Number
 Boolean
o Composite (or reference)
 Object
 Array
 Functions
o Special data types
 Undefined
 Null

String Data Type

 The string data type is used to represent textual data (i.e. sequences of characters).
Strings are created using single or double quotes surrounding one or more characters,
as shown below:

var a = 'Hi there!'; // using single quotes


var b = "Hi there!"; // using double quotes

 You can include quotes inside the string as long as they don't match the enclosing
quotes.

PANGASINAN STATE UNIVERSITY 5


FM-AA-CIA-15 Rev. 0 10-July-2020

Study Guide in WD101 Web Development Module No. 8

var a = "Let's have a cup of coffee."; // single quote inside double


quotes

var b = 'He said "Hello" and left.'; // double quotes inside single quotes

var c = 'We\'ll never give up.'; // escaping single quote with backslash

Number Data Type

 The number data type is used to represent positive or negative numbers with or without
decimal place, or numbers written using exponential notation e.g. 1.5e-4 (equivalent to
1.5x10-4).

var a = 25; // integer


var b = 80.5; // floating-point number
var c = 4.25e+6; // exponential notation, same as 4.25e6 or 4250000
var d = 4.25e-6; // exponential notation, same as 0.00000425

Boolean Data Type

 The Boolean data type can hold only two values: true or false. It is typically used to
store values like yes (true) or no (false), on (true) or off (false), etc. as demonstrated
below:

var isReading = true; // yes, I'm reading


var isSleeping = false; // no, I'm not sleeping

 Boolean values also come as a result of comparisons in a program. The following


example compares two variables and shows the result in an alert dialog box:

var a = 2, b = 5, c = 10;

alert(b > a) // Output: true


alert(b > c) // Output: false

Undefined Data Type

 The undefined data type can only have one value-the special value undefined. If a
variable has been declared, but has not been assigned a value, has the value
“undefined”.

var a;
var b = "Hello World!"

alert(a) // Output: undefined


alert(b) // Output: Hello World!

Null Data Type

 This is another special data type that can have only one value-the null value. A null
value means that there is no value. It is not equivalent to an empty string ("") or 0, it is
simply nothing.
 A variable can be explicitly emptied of its current contents by assigning it the null value.

PANGASINAN STATE UNIVERSITY 6


FM-AA-CIA-15 Rev. 0 10-July-2020

Study Guide in WD101 Web Development Module No. 8

var a = null;
alert(a); // Output: null

var b = "Hello World!"


alert(b); // Output: Hello World!

b = null;
alert(b) // Output: null

Object Data Type

 The object is a complex data type that allows you to store collections of data.
 An object contains properties, defined as a key-value pair. A property key (name) is
always a string, but the value can be any data type, like strings, numbers, booleans, or
complex data types like arrays, function and other objects. You'll learn more about
objects in upcoming chapters.
 The following example will show you the simplest way to create an object in JavaScript.

var emptyObject = {};


var person = {"name": "Clark", "surname": "Kent", "age": "36"};

// For better reading


var car = {
"modal": "BMW X3",
"color": "white",
"doors": 5
}

 You can omit the quotes around property name if the name is a valid JavaScript name.
That means quotes are required around "first-name" but are optional around firstname.
So the car object in the above example can also be written as:

var car = {
modal: "BMW X3",
color: "white",
doors: 5
}

Array Data Type

 An array is a type of object used for storing multiple values in single variable. Each value
(also called an element) in an array has a numeric position, known as its index, and it
may contain data of any data type-numbers, strings, booleans, functions, objects, and
even other arrays. The array index starts from 0, so that the first array element is arr[0]
not arr[1].

 The simplest way to create an array is by specifying the array elements as a comma-
separated list enclosed by square brackets, as shown in the example below:

var colors = ["Red", "Yellow", "Green", "Orange"];


var cities = ["London", "Paris", "New York"];

alert(colors[0]); // Output: Red


alert(cities[2]); // Output: New York

Function Data Type

PANGASINAN STATE UNIVERSITY 7


FM-AA-CIA-15 Rev. 0 10-July-2020

Study Guide in WD101 Web Development Module No. 8

 The function is callable object that executes a block of code. Since functions are objects,
so it is possible to assign them to variables, as shown in the example below:

var greeting = function(){


return "Hello World!";
}

// Check the type of greeting variable


alert(typeof greeting) // Output: function
alert(greeting()); // Output: Hello World!

 In fact, functions can be used at any place any other value can be used. Functions can
be stored in variables, objects, and arrays. Functions can be passed as arguments to
other functions, and functions can be returned from functions. Consider the following
function:

function createGreeting(name){
return "Hello, " + name;
}
function displayGreeting(greetingFunction, userName){
return greetingFunction(userName);
}

var result = displayGreeting(createGreeting, "Peter");


alert(result); // Output: Hello, Peter

LEARNING CONTENTS (Conditional and Looping Statements)

 While writing a program, there may be a situation when you need to adopt one out of a
given set of paths. In such cases, you need to use conditional statements that allow your
program to make correct decisions and perform right actions.
 JavaScript supports conditional statements which are used to perform different actions
based on different conditions. Here we will explain the if..else statement.

Image 1. Flowchart for if-else statement

The if Statement

PANGASINAN STATE UNIVERSITY 8


FM-AA-CIA-15 Rev. 0 10-July-2020

Study Guide in WD101 Web Development Module No. 8

 The if statement is used to execute a block of code only if the specified condition
evaluates to true. This is the simplest JavaScript's conditional statements and can be
written like:

if(condition) {
// Code to be executed
}

Example:
The following example will output "Have a nice weekend!" if the current day is Friday:

var now = new Date();


var dayOfWeek = now.getDay(); // Sunday - Saturday : 0 - 6

if(dayOfWeek == 5) {
alert("Have a nice weekend!");
}

The if...else Statement

 You can enhance the decision making capabilities of your JavaScript program by
providing an alternative choice through adding an else statement to the if statement.

 The if...else statement allows you to execute one block of code if the specified condition
is evaluates to true and another block of code if it is evaluates to false. It can be written,
like this:

if(condition) {
// Code to be executed if condition is true
} else {
// Code to be executed if condition is false
}

Example:

The JavaScript code in the following example will output "Have a nice weekend!" if the
current day is Friday, otherwise it will output the text "Have a nice day!"

var now = new Date();


var dayOfWeek = now.getDay(); // Sunday - Saturday : 0 - 6

if(dayOfWeek == 5) {
alert("Have a nice weekend!");
} else {
alert("Have a nice day!");
}

The if...else if...else Statement

 The if...else if...else a special statement that is used to combine multiple if...else
statements.

if(condition1) {

PANGASINAN STATE UNIVERSITY 9


FM-AA-CIA-15 Rev. 0 10-July-2020

Study Guide in WD101 Web Development Module No. 8

// Code to be executed if condition1 is true


} else if(condition2) {
// Code to be executed if the condition1 is false and condition2 is true
} else {
// Code to be executed if both condition1 and condition2 are false
}

Example:

The following example will output "Have a nice weekend!" if the current day is Friday,
and "Have a nice Sunday!" if the current day is Sunday, otherwise it will output "Have a
nice day!"

var now = new Date();


var dayOfWeek = now.getDay(); // Sunday - Saturday : 0 - 6

if(dayOfWeek == 5) {
alert("Have a nice weekend!");
} else if(dayOfWeek == 0) {
alert("Have a nice Sunday!");
} else {
alert("Have a nice day!");
}

Switch...Case Statement

 The switch..case statement is an alternative to the if...else if...else statement, which


does almost the same thing. The switch...case statement tests a variable or expression
against a series of values until it finds a match, and then executes the block of code
corresponding to that match. It's syntax is:

switch(x){
case value1:
// Code to be executed if x === value1
break;
case value2:
// Code to be executed if x === value2
break;
...
default:
// Code to be executed if x is different from all values
}

Example:
Consider the following example, which display the name of the day of the week.

var d = new Date();

switch(d.getDay()) {
case 0:
alert("Today is Sunday.");
break;
case 1:
alert("Today is Monday.");
break;
case 2:

PANGASINAN STATE UNIVERSITY 10


FM-AA-CIA-15 Rev. 0 10-July-2020

Study Guide in WD101 Web Development Module No. 8

alert("Today is Tuesday.");
break;
case 3:
alert("Today is Wednesday.");
break;
case 4:
alert("Today is Thursday.");
break;
case 5:
alert("Today is Friday.");
break;
case 6:
alert("Today is Saturday.");
break;
default:
alert("No information available for that day.");
break;
}

while Loop

 The most basic loop in JavaScript is the while loop which would be discussed in this
chapter. The purpose of a while loop is to execute a statement or code block repeatedly
as long as an expression is true. Once the expression becomes false, the loop
terminates.

Image 2. Flowchart for while loop statement

 The generic syntax of the while loop is:

PANGASINAN STATE UNIVERSITY 11


FM-AA-CIA-15 Rev. 0 10-July-2020

Study Guide in WD101 Web Development Module No. 8

while(condition) {
// Code to be executed
}

 The following example defines a loop that will continue to run as long as the variable i is
less than or equal to 5. The variable i will increase by 1 each time the loop runs:

var i = 1;
while(i <= 5) {
document.write("<p>The number is " + i + "</p>");
i++;
}

do...while Loop

 The do...while loop is similar to the while loop except that the condition check happens
at the end of the loop. This means that the loop will always be executed at least once,
even if the condition is false.

Image 3. Flowchart for do…while loop statement

 The generic syntax of the do-while loop is:

do {
// Code to be executed
}
while(condition);

 The JavaScript code in the following example defines a loop that starts with i=1. It will
then print the output and increase the value of variable i by 1. After that the condition is
evaluated, and the loop will continue to run as long as the variable i is less than, or
equal to 5.

var i = 1;
do {

PANGASINAN STATE UNIVERSITY 12


FM-AA-CIA-15 Rev. 0 10-July-2020

Study Guide in WD101 Web Development Module No. 8

document.write("<p>The number is " + i + "</p>");


i++;
}
while(i <= 5);

for Loop

 The for loop repeats a block of code as long as a certain condition is met. It is typically
used to execute a block of code for certain number of times.

Image 4. Flowchart for For loop statement

 The parameters of the for loop statement have following meanings:


o initialization — it is used to initialize the counter variables, and evaluated once
unconditionally before the first execution of the body of the loop.
o condition — it is evaluated at the beginning of each iteration. If it evaluates to
true, the loop statements execute. If it evaluates to false, the execution of the
loop ends.
o increment — it updates the loop counter with a new value each time the loop
runs.

 The following example defines a loop that starts with i=1. The loop will continued until
the value of variable i is less than or equal to 5. The variable i will increase by 1 each
time the loop runs:

for(var i=1; i<=5; i++) {


document.write("<p>The number is " + i + "</p>");
}

LEARNING ACTIVITY 2

1. Write a JavaScript program that accept two integers and display the larger
2. Write a JavaScript conditional statement to sort three numbers. Display an alert box
to show the result.
3. Write a JavaScript conditional statement to find the largest of five numbers. Display
an alert box to show the result.

PANGASINAN STATE UNIVERSITY 13


FM-AA-CIA-15 Rev. 0 10-July-2020

Study Guide in WD101 Web Development Module No. 8

4. Write a JavaScript for loop that will iterate from 0 to 15. For each iteration, it will
check if the current number is odd or even, and display a message to the screen.

Sample output

"0 is even"
"1 is odd"
"2 is even"

LEARNING CONTENTS (Arrays in JavaScript)

LEARNING CONTENTS (Arrays)

What is Array?

 Arrays are complex variables that allow us to store more than one value or a group of
values under a single variable name.
 JavaScript arrays can store any valid value, including strings, numbers, objects,
functions, and even other arrays, thus making it possible to create more complex data
structures such as an array of objects or an array of arrays.
 If you have a list of items (a list of car names, for example), storing the cars in single
variables could look like this:

var car1 = "Saab";


var car2 = "Volvo";
var car3 = "BMW";

 However, what if you want to loop through the cars and find a specific one? And what if
you had not 3 cars, but 300?
 The solution is using an array. For an array can hold many values under a single name,
and you can access the values by referring to an index number.

Creating an Array

 Using an array literal is the easiest way to create a JavaScript Array.

var array_name = [item1, item2, ...];

Example: Here are some examples of arrays created using array literal syntax:

var cars = ["Saab", "Volvo", "BMW"];


var colors = ["Red", "Green", "Blue"];
var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];
var cities = ["London", "Paris", "New York"];
var person = ["John", "Wick", 32];

Accessing the Elements of an Array

 Array elements can be accessed by their index using the square bracket notation. An
index is a number that represents an element's position in an array.

 Array indexes are zero-based. This means that the first item of an array is stored at
index 0, not 1, the second item is stored at index 1, and so on. Array indexes start at 0

PANGASINAN STATE UNIVERSITY 14


FM-AA-CIA-15 Rev. 0 10-July-2020

Study Guide in WD101 Web Development Module No. 8

and go up to the number of elements minus 1. So, array of five elements would have
indexes from 0 to 4.

 The following example will show you how to get individual array element by their index.

var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];

document.write(fruits[0]); // Prints: Apple


document.write(fruits[1]); // Prints: Banana
document.write(fruits[2]); // Prints: Mango
document.write(fruits[fruits.length - 1]); // Prints: Papaya

Getting the Length of an Array

 The length property returns the length of an array, which is the total number of
elements contained in the array. Array length is always greater than the index of any of
its element.

var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];


document.write(fruits.length); // Prints: 5

Looping Through Array Elements

 You can use for loop to access each element of an array in sequential order, like this:

var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];

// Iterates over array elements


for(var i = 0; i < fruits.length; i++) {
document.write(fruits[i] + "<br>"); // Print array element
}

 ECMAScript 6 has introduced a simpler way to iterate over array element, which is for-of
loop. In this loop you don't have to initialize and keep track of the loop counter variable
(i).
 Here's the same example rewritten using the for-of loop

var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];

// Iterates over array elements


for(var fruit of fruits) {
document.write(fruit + "<br>"); // Print array element
}
 You can also iterate over the array elements using for-in loop, like this:

var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];

// Loop through all the elements in the array


for(var i in fruits) {
document.write(fruits[i] + "<br>");
}

Adding an Element to an Array

 To add a new element at the end of an array, simply use the push() method, like this:

var colors = ["Red", "Green", "Blue"];

PANGASINAN STATE UNIVERSITY 15


FM-AA-CIA-15 Rev. 0 10-July-2020

Study Guide in WD101 Web Development Module No. 8

colors.push("Yellow");

document.write(colors); // Prints: Red,Green,Blue,Yellow


document.write(colors.length); // Prints: 4

 Similarly, to add a new element at the beginning of an array use the unshift() method,
like this:

var colors = ["Red", "Green", "Blue"];


colors.unshift("Yellow");

document.write(colors); // Prints: Yellow,Red,Green,Blue


document.write(colors.length); // Prints: 4

 You can also add multiple elements at once using the push() and unshift() methods, like
this:

var colors = ["Red", "Green", "Blue"];


colors.push("Pink", "Voilet");
colors.unshift("Yellow", "Grey");

document.write(colors); // Prints: Yellow,Grey,Red,Green,Blue,Pink,Voilet


document.write(colors.length); // Prints: 7

Removing Elements from an Array

 To remove the last element from an array you can use the pop() method. This method
returns the value that was popped out. Here's an example:

var colors = ["Red", "Green", "Blue"];


var last = colors.pop();

document.write(last); // Prints: Blue


document.write(colors.length); // Prints: 2

 Similarly, you can remove the first element from an array using the shift() method. This
method also returns the value that was shifted out. Here's an example:

var colors = ["Red", "Green", "Blue"];


var first = colors.shift();

document.write(first); // Prints: Red


document.write(colors.length); // Prints: 2

 Additional Note:

The push() and pop() methods runs faster than unshift() and shift().
Because push() and pop() methods simply add and remove elements at
the end of an array therefore the elements do not move, whereas unshift()
and shift() add and remove elements at the beginning of the array that
require re-indexing of whole array.
CTIVITY 1
Creating a String from an Array

 There may be situations where you simply want to create a string by joining the
elements of an array. To do this you can use the join() method. This method takes an

PANGASINAN STATE UNIVERSITY 16


FM-AA-CIA-15 Rev. 0 10-July-2020

Study Guide in WD101 Web Development Module No. 8

optional parameter which is a separator string that is added in between each element. If
you omit the separator, then JavaScript will use comma (,) by default. The following
example shows how it works:

var colors = ["Red", "Green", "Blue"];

document.write(colors.join()); // Prints: Red,Green,Blue


document.write(colors.join("")); // Prints: RedGreenBlue
document.write(colors.join("-")); // Prints: Red-Green-Blue
document.write(colors.join(", ")); // Prints: Red, Green, Blue

 You can also convert an array to a comma-separated string using the toString(). This
method does not accept the separator parameter like join(). Here's an example:

var colors = ["Red", "Green", "Blue"];


document.write(colors.toString()); // Prints: Red,Green,Blue

Extracting a Portion of an Array

 If you want to extract out a portion of an array (i.e. subarray) but keep the original
array intact you can use the slice() method. This method takes 2 parameters: start
index (index at which to begin extraction), and an optional end index (index before
which to end extraction), like arr.slice(startIndex, endIndex). Here's an example:

var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];


var subarr = fruits.slice(1, 3);
document.write(subarr); // Prints: Banana,Mango

 If endIndex parameter is omitted, all elements to the end of the array are extracted. You
can also specify negative indexes or offsets —in that case the slice() method extract the
elements from the end of an array, rather then the begining. For example:

var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];

document.write(fruits.slice(2)); // Prints: Mango,Orange,Papaya


document.write(fruits.slice(-2)); // Prints: Orange,Papaya
document.write(fruits.slice(2, -1)); // Prints: Mango,Orange

Merging Two or More Arrays

 The concat() method can be used to merge or combine two or more arrays. This method
does not change the existing arrays, instead it returns a new array. For example:

var pets = ["Cat", "Dog", "Parrot"];


var wilds = ["Tiger", "Wolf", "Zebra"];

// Creating new array by combining pets and wilds arrays


var animals = pets.concat(wilds);
document.write(animals); // Prints: Cat,Dog,Parrot,Tiger,Wolf,Zebra

 The concat() method can take any number of array arguments, so you can create an
array from any number of other arrays, as shown in the following example:

var pets = ["Cat", "Dog", "Parrot"];


var wilds = ["Tiger", "Wolf", "Zebra"];

PANGASINAN STATE UNIVERSITY 17


FM-AA-CIA-15 Rev. 0 10-July-2020

Study Guide in WD101 Web Development Module No. 8

var bugs = ["Ant", "Bee"];

// Creating new array by combining pets, wilds and bugs arrays


var animals = pets.concat(wilds, bugs);
document.write(animals); // Prints:
Cat,Dog,Parrot,Tiger,Wolf,Zebra,Ant,Bee

Searching Through an Array

 If you want to search an array for a specific value, you can simply use the indexOf() and
lastIndexOf(). If the value is found, both methods return an index representing the array
element. If the value is not found, -1 is returned. The indexOf() method returns the first
one found, whereas the lastIndexOf() returns the last one found.

var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];

document.write(fruits.indexOf("Apple")); // Prints: 0
document.write(fruits.indexOf("Banana")); // Prints: 1
document.write(fruits.indexOf("Pineapple")); // Prints: -1

 Both methods also accept an optional integer parameter from index which specifies the
index within the array at which to start the search. Here's an example:

var arr = [1, 0, 3, 1, false, 5, 1, 4, 7];

// Searching forwards, starting at from- index


document.write(arr.indexOf(1, 2)); // Prints: 3

// Searching backwards, starting at from index


document.write(arr.lastIndexOf(1, 2)); // Prints: 0

 You can also use includes() method to find out whether an array includes a certain
element or not. This method takes the same parameters as indexOf() and lastIndexOf()
methods, but it returns true or false instead of index number. For example:

var arr = [1, 0, 3, 1, false, 5, 1, 4, 7];

document.write(arr.includes(1)); // Prints: true


document.write(arr.includes(6)); // Prints: false
document.write(arr.includes(1, 2)); // Prints: true
document.write(arr.includes(3, 4)); // Prints: false

 If you want to search an array based on certain condition then you can use the
JavaScript find() method which is newly introduced in ES6. This method returns the
value of the first element in the array that satisfies the provided testing function.
Otherwise it return undefined.

var arr = [1, 0, 3, 1, false, 5, 1, 4, 7];

var result = arr.find(function(element) {


return element > 4;
});
document.write(result); // Prints: 5

PANGASINAN STATE UNIVERSITY 18


FM-AA-CIA-15 Rev. 0 10-July-2020

Study Guide in WD101 Web Development Module No. 8

 There is one more method similar to find() is findIndex() method, which returns the
index of a found element in the array instead of its value. For example:

var arr = [1, 0, 3, 1, false, 5, 1, 4, 7];

var result = arr.findIndex(function(element) {


return element > 6;
});
document.write(result); // Prints: 8

 The find() method only looks for the first element that satisfies the provided testing
function. However, if you want to find out all the matched elements you can use the
filter() method.
 The filter() method creates a new array with all the elements that successfully passes
the given test. The following example will show you how this actually works:

var arr = [1, 0, 3, 1, false, 5, 1, 4, 7];

var result = arr.filter(function(element) {


return element > 4;
});
document.write(result); // Prints: 5,7
document.write(result.length); // Prints: 2

Sorting Arrays

 Sorting is a common task when working with arrays. It would be used, for instance, if
you want to display the city or county names in alphabetical order.
 The JavaScript Array object has a built-in method sort() for sorting array elements in
alphabetical order. The following example demonstrates how it works:

var fruits = ["Banana", "Orange", "Apple", "Papaya", "Mango"];


var sorted = fruits.sort();

alert(fruits); // Outputs: Apple,Banana,Mango,Orange,Papaya


alert(sorted); // Outputs: Apple,Banana,Mango,Orange,Papaya

Reversing an Array

 You can use the reverse() method to reverse the order of the elements of an array.
 This method reverses an array in such a way that the first array element becomes the
last, and the last array element becomes the first. Here's an example:

var counts = ["one", "two", "three", "four", "five"];


var reversed = counts.reverse();

alert(counts); // Outputs: five,four,three,two,one


alert(reversed); // Output: five,four,three,two,one

Sorting Numeric Arrays

 The sort() method may produce unexpected result when it is applied on the numeric
arrays (i.e. arrays containing numeric values). For instance:

var numbers = [5, 20, 10, 75, 50, 100];

PANGASINAN STATE UNIVERSITY 19


FM-AA-CIA-15 Rev. 0 10-July-2020

Study Guide in WD101 Web Development Module No. 8

numbers.sort(); // Sorts numbers array


alert(numbers); // Outputs: 10,100,20,5,50,75

 As you can see, the result is different from what we've expected. It happens because,
the sort() method sorts the numeric array elements by converting them to strings (i.e.
20 becomes "20", 100 becomes "100", and so on), and since the first character of string
"20" (i.e. "2") comes after the first character of string "100" (i.e. "1"), that's why the
value 20 is sorted after the 100.
 To fix this sorting problem with numeric array, you can pass a compare function, like
this:

var numbers = [5, 20, 10, 75, 50, 100];

// Sorting an array using compare function


numbers.sort(function(a, b) {
return a - b;
});
alert(numbers); // Outputs: 5,10,20,50,75,100

 As you can see, this time we've got the correct result. Let's see how it works.

 When compare function is specified, array elements are sorted according to the return
value of the compare function. For example, when comparing a and b:

1. If the compare function returns a value less than 0, then a comes first.
2. If the compare function returns a value greater than 0, then b comes first.
3. If the compare function returns 0, a and b remain unchanged with respect to
each other, but sorted with respect to all other elements.

 Hence, since 5 - 20 = -15 which is less than 0, therefore 5 comes first, similarly 20 - 10
= 10 which is greater than 0, therefore 10 comes before 20, likewise 20 - 75 = -55
which is less than 0, so 20 comes before 75, similarly 50 comes before 75, and so on.

Finding the Maximum and Minimum Value in an Array

 You can use the apply() method in combination with the Math.max() and Math.min() to
find the maximum and minimum value inside an array, like this:

var numbers = [3, -7, 10, 8, 15, 2];

// Defining function to find maximum value


function findMax(array) {
return Math.max.apply(null, array);
}

// Defining function to find minimum value


function findMin(array) {
return Math.min.apply(null, array);
}

alert(findMax(numbers)); // Outputs: 15
alert(findMin(numbers)); // Outputs: -7

Sorting an Array of Objects

 The sort() method can also be used for sorting object arrays using the compare function.

PANGASINAN STATE UNIVERSITY 20


FM-AA-CIA-15 Rev. 0 10-July-2020

Study Guide in WD101 Web Development Module No. 8

 The following example will show you how to sort an array of objects by property values:

var persons = [
{ name: "Harry", age: 14 },
{ name: "Ethan", age: 30 },
{ name: "Peter", age: 21 },
{ name: "Clark", age: 42 },
{ name: "Alice", age: 16 }
];

// Sort by age
persons.sort(function (a, b) {
return a.age - b.age;
});

console.log(persons);

// Sort by name
persons.sort(function(a, b) {
var x = a.name.toLowerCase(); // ignore upper and lowercase
var y = b.name.toLowerCase(); // ignore upper and lowercase
if(x < y) {
return -1;
}
if(x > y) {
return 1;
}
// names must be equal
return 0;
});

console.log(persons);

LEARNING ACTIVITY 3

1. Write a simple JavaScript program to join all elements of the following array into a string
a. Sample array : myColor = ["Red", "Green", "White", "Black"];
2. Write a JavaScript program which accept a number as input and insert dashes (-)
between each two even numbers.

LEARNING CONTENTS (Functions in JavaScript)

What is a Function?

 A function is a group of statements that perform specific tasks and can be kept and
maintained separately form main program. Functions provide a way to create reusable
code packages which are more portable and easier to debug. Here are some advantages
of using functions:
1. Functions reduces the repetition of code within a program
2. Functions makes the code much easier to maintain
3. Functions makes it easier to eliminate the errors

Defining and Calling a Function

PANGASINAN STATE UNIVERSITY 21


FM-AA-CIA-15 Rev. 0 10-July-2020

Study Guide in WD101 Web Development Module No. 8

 The declaration of a function start with the function keyword, followed by the name of
the function you want to create, followed by parentheses i.e. () and finally place your
function's code between curly brackets {}. Here's the basic syntax for declaring a
function:

function functionName() {
// Code to be executed
}

 Here is a simple example of a function, that will show a hello message:

// Defining function
function sayHello() {
alert("Hello, welcome to this website!");
}

// Calling function
sayHello(); // 0utputs: Hello, welcome to this website!

 Once a function is defined it can be called (invoked) from anywhere in the document, by
typing its name followed by a set of parentheses, like sayHello() in the example above.
 A function name must start with a letter or underscore character not with a number,
optionally followed by the more letters, numbers, or underscore characters. Function
names are case sensitive, just like variable names.

Adding Parameters to Functions

 You can specify parameters when you define your function to accept input values at run
time. The parameters work like placeholder variables within a function; they're replaced
at run time by the values (known as argument) provided to the function at the time of
invocation.

 Parameters are set on the first line of the function inside the set of parentheses, like
this:

function functionName(parameter1, parameter2, parameter3) {


// Code to be executed
}

 The displaySum() function in the following example takes two numbers as arguments,
simply add them together and then display the result in the browser.

// Defining function
function displaySum(num1, num2) {
var total = num1 + num2;
alert(total);
}

// Calling function
displaySum(6, 20); // 0utputs: 26
displaySum(-5, 17); // 0utputs: 12

 You can define as many parameters as you like. However for each parameter you
specify, a corresponding argument needs to be passed to the function when it is called,
otherwise its value becomes undefined. Let's consider the following example:

PANGASINAN STATE UNIVERSITY 22


FM-AA-CIA-15 Rev. 0 10-July-2020

Study Guide in WD101 Web Development Module No. 8

// Defining function
function showFullname(firstName, lastName) {
alert(firstName + " " + lastName);
}

// Calling function
showFullname("Clark", "Kent"); // 0utputs: Clark Kent
showFullname("John"); // 0utputs: John undefined

Default Values for Function Parameters ES6

 With ES6, now you can specify default values to the function parameters. This means
that if no arguments are provided to function when it is called these default parameters
values will be used. This is one of the most awaited features in JavaScript. Here's an
example:

function sayHello(name = 'Guest') {


alert('Hello, ' + name);
}

sayHello(); // 0utputs: Hello, Guest


sayHello('John'); // 0utputs: Hello, John

 While prior to ES6, to achieve the same we had to write something like this:

function sayHello(name) {
var name = name || 'Guest';
alert('Hello, ' + name);
}

sayHello(); // 0utputs: Hello, Guest


sayHello('John'); // 0utputs: Hello, John

Returning Values from a Function

 A function can return a value back to the script that called the function as a result using
the return statement. The value may be of any type, including arrays and objects.
 The return statement usually placed as the last line of the function before the closing
curly bracket and ends it with a semicolon, as shown in the following example.

// Defining function
function getSum(num1, num2) {
var total = num1 + num2;
return total;
}

// Displaying returned value


alert(getSum(6, 20)); // 0utputs: 26
alert(getSum(-5, 17)); // 0utputs: 12

 A function cannot return multiple values. However, you can obtain similar results by
returning an array of values, as demonstrated in the following example.

PANGASINAN STATE UNIVERSITY 23


FM-AA-CIA-15 Rev. 0 10-July-2020

Study Guide in WD101 Web Development Module No. 8

// Defining function
function divideNumbers(dividend, divisor){
var quotient = dividend / divisor;
var arr = [dividend, divisor, quotient];
return arr;
}

// Store returned value in a variable


var all = divideNumbers(10, 2);

// Displaying individual values


alert(all[0]); // 0utputs: 10
alert(all[1]); // 0utputs: 2
alert(all[2]); // 0utputs: 5

LEARNING ACTIVITY 4

1. Write a JavaScript function that reverse a number.


2. Write a JavaScript function that checks whether a passed string is palindrome or not?
3. Write a JavaScript function that returns a passed string with letters in alphabetical
order.

LEARNING CONTENTS (Event Handlers)

What is an event?

 An event is something that happens when user interact with the web page, such as when
he clicked a link or button, entered text into an input box or textarea, made selection in
a select box, pressed key on the keyboard, moved the mouse pointer, submits a form,
etc. In some cases, the Browser itself can trigger the events, such as the page load and
unload events.

 By convention, the names for event handlers always begin with the word "on", so an
event handler for the click event is called onclick, similarly an event handler for the load
event is called onload, event handler for the blur event is called onblur, and so on.

 There are several ways to assign an event handler. The simplest way is to add them
directly to the start tag of the HTML elements using the special event-handler attributes.
For example, to assign a click handler for a button element, we can use onclick attribute,
like this:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript Attaching Event Handlers Inline</title>
</head>
<body>
<button type="button" onclick="alert('Hello World!')">Click Me</button>
</body>

PANGASINAN STATE UNIVERSITY 24


FM-AA-CIA-15 Rev. 0 10-July-2020

Study Guide in WD101 Web Development Module No. 8

</html>

 However, to keep the JavaScript seperate from HTML, you can set up the event handler
in an external JavaScript file or within the <script> and </script> tags, like this:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript Attaching Event Handlers in External File</title>
</head>
<body>
<button type="button" id="myBtn">Click Me</button>
<script>
function sayHello(){
alert('Hello World!');
}
document.getElementById("myBtn").onclick = sayHello;
</script>
</body>
</html>

Output:

Mouse Events

 A mouse event is triggered when the user click some element, move the mouse pointer
over an element, etc. Here're some most important mouse events and their event
handler.

The Click Event (onclick)

 The click event occurs when a user clicks on an element on a web page. Often, these are
form elements and links. You can handle a click event with an onclick event handler.
 The following example will show you an alert message when you click on the elements.

<button type="button" onclick="alert('You have clicked a button!');">Click


Me</button>
<a href="#" onclick="alert('You have clicked a link!');">Click Me</a>

PANGASINAN STATE UNIVERSITY 25


FM-AA-CIA-15 Rev. 0 10-July-2020

Study Guide in WD101 Web Development Module No. 8

The Contextmenu Event (oncontextmenu)

 The contextmenu event occurs when a user clicks the right mouse button on an element
to open a context menu. You can handle a contextmenu event with an oncontextmenu
event handler.
 The following example will show an alert message when you right-click on the elements.

<button type="button" oncontextmenu="alert('You have right-clicked a


button!');">Right Click on Me</button>

<a href="#" oncontextmenu="alert('You have right-clicked a link!');">Right


Click on Me</a>

The Mouseover Event (onmouseover)

 The mouseover event occurs when a user moves the mouse pointer over an element.
 You can handle the mouseover event with the onmouseover event handler. The following
example will show you an alert message when you place mouse over the elements.

<button type="button" onmouseover="alert('You have placed mouse pointer


over a button!');">Place Mouse Over Me</button>

<a href="#" onmouseover="alert('You have placed mouse pointer over a


link!');">Place Mouse Over Me</a>

The Mouseout Event (onmouseout)

 The mouseout event occurs when a user moves the mouse pointer outside of an
element.
 You can handle the mouseout event with the onmouseout event handler. The following
example will show you an alert message when the mouseout event occurs.

<button type="button" onmouseout="alert('You have moved out of the


button!');">Place Mouse Inside Me and Move Out</button>

<a href="#" onmouseout="alert('You have moved out of the link!');">Place


Mouse Inside Me and Move Out</a>

Keyboard Events

 A keyboard event is fired when the user press or release a key on the keyboard. Here're
some most important keyboard events and their event handler.

The Keydown Event (onkeydown)

 The keydown event occurs when the user presses down a key on the keyboard.
 You can handle the keydown event with the onkeydown event handler. The following
example will show you an alert message when the keydown event occurs.

<input type="text" onkeydown="alert('You have pressed a key inside text


input!')">

<textarea onkeydown="alert('You have pressed a key inside


textarea!')"></textarea>

PANGASINAN STATE UNIVERSITY 26


FM-AA-CIA-15 Rev. 0 10-July-2020

Study Guide in WD101 Web Development Module No. 8

The Keyup Event (onkeyup)

 The keyup event occurs when the user releases a key on the keyboard.
 You can handle the keyup event with the onkeyup event handler. The following example
will show you an alert message when the keyup event occurs.

<input type="text" onkeyup="alert('You have released a key inside text


input!')">

<textarea onkeyup="alert('You have released a key inside


textarea!')"></textarea>

The Keypress Event (onkeypress)

 The keypress event occurs when a user presses down a key on the keyboard that has a
character value associated with it. For example, keys like Ctrl, Shift, Alt, Esc, Arrow
keys, etc. will not generate a keypress event, but will generate a keydown and keyup
event.

 You can handle the keypress event with the onkeypress event handler. The following
example will show you an alert message when the keypress event occurs.

<input type="text" onkeypress="alert('You have pressed a key inside text


input!')">

<textarea onkeypress="alert('You have pressed a key inside


textarea!')"></textarea>

Form Events

 A form event is fired when a form control receive or loses focus or when the user modify
a form control value such as by typing text in a text input, select any option in a select
box etc. Here're some most important form events and their event handler.

The Focus Event (onfocus)

 The focus event occurs when the user gives focus to an element on a web page.

 You can handle the focus event with the onfocus event handler. The following example
will highlight the background of text input in yellow color when it receives the focus.

<script>
function highlightInput(elm){
elm.style.background = "yellow";
}
</script>
<input type="text" onfocus="highlightInput(this)">
<button type="button">Button</button>

The Change Event (onchange)

 The change event occurs when a user changes the value of a form element.

 You can handle the change event with the onchange event handler. The following
example will show you an alert message when you change the option in the select box.

PANGASINAN STATE UNIVERSITY 27


FM-AA-CIA-15 Rev. 0 10-July-2020

Study Guide in WD101 Web Development Module No. 8

<select onchange="alert('You have changed the selection!');">


<option>Select</option>
<option>Male</option>
<option>Female</option>
</select>

The Submit Event (onsubmit)

 The submit event only occurs when the user submits a form on a web page.

 You can handle the submit event with the onsubmit event handler. The following
example will show you an alert message while submitting the form to the server.

<form action="action.php" method="post" onsubmit="alert('Form data will be


submitted to the server!');">
<label>First Name:</label>
<input type="text" name="first-name" required>
<input type="submit" value="Submit">
</form>

SUMMARY

 JavaScript is a lightweight, interpreted programming language.


 JavaScript is officially maintained by ECMA (European Computer Manufacturers
Association) as ECMAScript. ECMAScript 6 (or ES6) is the latest major version of the
ECMAScript standard.
 There are three ways to add JavaScript to your web page
o Embedded JavaScript
o External JavaScript
o Inline JavaScript
 Arrays are complex variables that allow us to store more than one value or a group of
values under a single variable name.
 Array elements can be accessed by their index using the square bracket notation. An
index is a number that represents an element's position in an array.
 Array indexes are zero-based. This means that the first item of an array is stored at
index 0, not 1, the second item is stored at index 1, and so on. Array indexes start at 0
and go up to the number of elements minus 1. So, array of five elements would have
indexes from 0 to 4.
 A function is a group of statements that perform specific tasks and can be kept and
maintained separately form main program.
 Functions provide a way to create reusable code packages which are more portable and
easier to debug.
 An event is something that happens when user interact with the web page, such as when
he clicked a link or button, entered text into an input box or textarea, made selection in
a select box, pressed key on the keyboard, moved the mouse pointer, submits a form,
etc. In some cases, the Browser itself can trigger the events, such as the page load and
unload events.
 By convention, the names for event handlers always begin with the word "on", so an
event handler for the click event is called onclick, similarly an event handler for the load
event is called onload, event handler for the blur event is called onblur, and so on.

PANGASINAN STATE UNIVERSITY 28


FM-AA-CIA-15 Rev. 0 10-July-2020

Study Guide in WD101 Web Development Module No. 8

REFERENCES

 https://www.tutorialrepublic.com/javascript-tutorial/
 https://javascript.info/
 https://www.guru99.com/interactive-javascript-tutorials.html
 https://www.tutorialspoint.com/javascript/index.htm

 JAVASCRIPT & JQUERY: interactive front-end web development by Jon Duckett

PANGASINAN STATE UNIVERSITY 29

You might also like