Module 08 Intro JS
Module 08 Intro JS
0 10-July-2020
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.
What is JavaScript?
History of 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.
CTIVITY 1
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.
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>
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:
Create an HTML file named “extenaljs.html” and place the following code in it:
<!DOCTYPE html>
<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>
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.
JavaScript Syntax
The syntax of JavaScript is the set of rules that define a correctly structured JavaScript
program.
Example:
var x = 5;
var y = 10;
var sum = x + y;
document.write(sum); // Prints variable value
JavaScript Comments
Example:
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?
var message;
Now, we can put some data into it by using the assignment operator =:
var message;
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!';
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:
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
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:
You can include quotes inside the string as long as they don't match the enclosing
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
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).
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 a = 2, b = 5, c = 10;
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!"
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.
var a = null;
alert(a); // Output: null
b = null;
alert(b) // Output: null
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.
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
}
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:
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:
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);
}
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.
The if Statement
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:
if(dayOfWeek == 5) {
alert("Have a nice weekend!");
}
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!"
if(dayOfWeek == 5) {
alert("Have a nice weekend!");
} else {
alert("Have a nice day!");
}
The if...else if...else a special statement that is used to combine multiple if...else
statements.
if(condition1) {
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!"
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
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.
switch(d.getDay()) {
case 0:
alert("Today is Sunday.");
break;
case 1:
alert("Today is Monday.");
break;
case 2:
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.
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.
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 {
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.
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:
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.
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"
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:
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
Example: Here are some examples of arrays created using array literal syntax:
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.
The following example will show you how to get individual array element by their index.
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.
You can use for loop to access each element of an array in sequential order, like this:
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
To add a new element at the end of an array, simply use the push() method, like this:
colors.push("Yellow");
Similarly, to add a new element at the beginning of an array use the unshift() method,
like this:
You can also add multiple elements at once using the push() and unshift() methods, like
this:
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:
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:
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
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:
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:
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:
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:
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:
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:
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.
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:
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:
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.
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:
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:
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:
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:
The sort() method may produce unexpected result when it is applied on the numeric
arrays (i.e. arrays containing numeric values). For instance:
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:
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.
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:
alert(findMax(numbers)); // Outputs: 15
alert(findMin(numbers)); // Outputs: -7
The sort() method can also be used for sorting object arrays using the compare function.
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.
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
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
}
// 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.
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:
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:
// Defining function
function showFullname(firstName, lastName) {
alert(firstName + " " + lastName);
}
// Calling function
showFullname("Clark", "Kent"); // 0utputs: Clark Kent
showFullname("John"); // 0utputs: John undefined
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:
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);
}
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;
}
A function cannot return multiple values. However, you can obtain similar results by
returning an array of values, as demonstrated in the following example.
// Defining function
function divideNumbers(dividend, divisor){
var quotient = dividend / divisor;
var arr = [dividend, divisor, quotient];
return arr;
}
LEARNING ACTIVITY 4
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>
</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 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.
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.
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.
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.
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 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.
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.
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.
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 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 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.
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.
SUMMARY
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