Grade 11 Web JavaScript
Grade 11 Web JavaScript
Interactivity To a Website
Contents
No Contents page
Module Description 572
1 UNIT 1: SCRIPTING LANGUAGE 573
1.1 Identify scripting language 584
1.2 Introduction to Javascript (JS) 585
Unit Summary 587
Unit Review Questions 588
2 UNIT 2: Apply INTERACTIVITY USING JAVASCRIPT 590
2.1 Overview of interactivity using Javascript 590
2.2 JavaScript Syntax and Basic Concepts 591
2.3 Control Structures and Loops 611
2.4 Functions in JavaScript 622
2.5 DOM Manipulation and Event Handling 636
2.6 Document Object Model (DOM) 636
Unit Summary 646
Unit Review Questions 646
3 UNIT 3: VALIDATING USER INPUT 649
3.1 Introduction to Validation 649
Unit Summary 655
Unit Review Questions 655
References 663
Grade 11 Web Design and Development Student Module
Module Description
The module "Apply interactivity to a website" refers to a specific section or unit of study that
focuses on teaching the concepts, techniques, and tools necessary to add dynamic and interactive
elements to a website. It typically covers topics related to client-side web development using
technologies such as HTML, CSS, and JavaScript.
The module may include the following key aspects:
• Identify scripting language
• Apply interactivity using JavaScript
• Validating User Input
Module Instruction:
For effectively use this module you are expected to follow the following module
instructions:
1. Read the learning outcomes of this module.
2. Learn study lessons in the module. Try to understand what are being discussed.
3. Accomplish the “Self-checks” which are placed following each topic. Then you are to get
the answer key at the end of the module to correct your answer only after you have
finished answering the Self-checks.
4. Accomplish unit review questions and practical activities which are placed at the end of
each unit. Then ask from your teacher/trainer the key to correction (answers key) or you
can request your teacher/trainer to correct your work.
5. Complete the ‘Project Work’ sited at the end of the module.
UNIT 1
SCRIPTING LANGUAGE
Unit Coverage
This unit is designed to provide you the necessary information and practice regarding the
following content coverage:
1.1. Introduction to JavaScript (JS)
5. Flexibility and rapid development: Scripting languages are often designed to prioritize
quick development and flexibility, allowing developers to write and modify code rapidly.
Examples of popular scripting languages include:
• JavaScript (primarily used for web development but can also be used for server-side
programming with [Link])
• Python, Ruby, PHP, Perl, Bash (shell scripting language), PowerShell, etc.
It's important to note that some languages can fall into both the scripting and general-purpose
categories, and the distinction between them can sometimes be blurry. However, these
characteristics can help you identify a language as a scripting language in most cases.
With the introduction of technologies like [Link], JavaScript can also be used for server-side
development, allowing developers to build full-stack web applications using a single language.
JavaScript is a cornerstone of modern web development. Its versatility extends beyond just
client- side scripting; it's also used on the server side ([Link]) and in mobile app development
(React Native, Native Script). JavaScript frameworks and libraries, such as React, Angular, and
Vue, have revolutionized how developers build user interfaces. The rise of Single Page
Applications (SPAs) and asynchronous programming, facilitated by JavaScript, has enhanced the
overall user experience on the web. In essence, JavaScript is an essential language for anyone
involved in web development.
• JavaScript is a MUST for students and working professionals to become a great Software
Engineer specially when they are working in Web Development Domain. I will list down
some of the key advantages of learning JavaScript:
• JavaScript is the most popular programming language in the world and that makes it a
programmer’s great choice. Once you learnt JavaScript, it helps you developing great front-
end as well as back-end software’s using different JavaScript based frameworks like jQuery,
[Link] etc.
• JavaScript is everywhere, it comes installed on every modern web browser and so to learn
JavaScript you really do not need any special environment setup. For example, Chrome,
Mozilla Firefox, Safari and every browser you know as of today, supports JavaScript.
• JavaScript helps you create really beautiful and crazy fast websites. You can develop your
website with a console like look and feel and give your users the best Graphical User
Experience.
• JavaScript usage has now extended to mobile app development, desktop app development,
and game development. This opens many opportunities for you as JavaScript Programmer.
• Due to high demand, there is tons of job growth and high pay for those who know JavaScript.
You can navigate over to different job sites to see what having JavaScript skills look like in
the job market.
• Great thing about JavaScript is that you will find tons of frameworks and Libraries already
developed which can be used directly in your software development to reduce your time to
market.
1.2.3. Features of JavaScript:
JavaScript offers several features that make it a powerful and versatile programming language
for web development.
Object Centered Language features built in the object as Java Script has a window object. Some
Common Examples of Object Centered languages are Java Script and Visual Basic etc. The
object-centered languages are mostly used for features like Polymorphism which is a quality of
taking an object in many forms.
The client is basically a term used for Web Browser in respective of User. The user gets access
to the client through a web browser for surfing and interacting through websites. The client edge
technology in Java Script allows the client to have full control over the content which is being
updated in servers.
Validation of User’s Input is most commonly known as form validation, it allows users to
interact with client through filling forms through web pages. The details in the form need to be
correctly filled where form validation helps the client to validate the details entered by the user.
5. Interpreter Centered
Java Script is built with Interpreter Centered which allows the user to get the output without the
use of Compiler. That means the input performed by the user gets rendered directly without the
compiling of codes.
Java Script has many In-Built Functions like isNAN (), Number (), parseFloat () and parseInt ()
etc. isNAN () Function is used to identify that input object is correct number format. parseFloat
() function is used in the conversion of the object into a number. parseInt () Function is used to
analyze strings.
The codes written in Java Script are Case Sensitive which explains that there will be no
difference in the output whether the codes are written in Upper Case or Lower-Case Format.
Java Script Features Light Weight and delicate and codes written in JavaScript don’t include
variables and uses only objects to perform the operations.
9. Statements Looping
The statement looping is used to perform the same operations repeatedly. In this operation the
same set of code run in repeat manner for a specific or unspecific set of time.
The Java Script has the ability to control operations updated on servers. This is basically
controlling the response on the website when the user tries to perform any operation the server
handled by the client like clicking on links and options, interaction response over the website,
etc.
JavaScript has a wide range of applications in web development. Some common use cases
include:
As mentioned before, Javascript is one of the most widely used programming languages
(Front- end as well as Back-end). It has its presence in almost every area of software
development. I'm going to list few of them here:
1. Client-side validation - This is really important to verify any user input before
submitting it to the server and Javascript plays an important role in validting those
inputs at front-end itself.
2. Manipulating HTML Pages - Javascript helps in manipulating HTML page on the
fly.
3. This helps in adding and deleting any HTML tag very easily using javascript and
modify your HTML to change its look and feel based on different devices and
requirements.
4. User Notifications - You can use Javascript to raise dynamic pop-ups on the
webpages to give different types of notifications to your website visitors.
5. Back-end Data Loading - Javascript provides Ajax library which helps in loading
back- end data while you are doing some other processing. This really gives an
amazing experience to your website visitors.
6. Presentations - JavaScript also provides the facility of creating presentations which
gives website look and feel. JavaScript provides RevealJS and BespokeJS libraries to
build web-based slide presentations.
7. Server Applications - Node JS is built on Chrome's Javascript runtime for building
fast and scalable network applications. This is an event-based library which helps in
developing very sophisticated server applications including Web Servers.
Advantages of JavaScript
• Less server interaction − You can validate user input before sending the page off to the
server. This saves server traffic, which means less load on your server.
• Immediate feedback to the visitors − They don't have to wait for a page reload to see if
they have forgotten to enter something.
• Increased interactivity − You can create interfaces that react when the user hovers over
them with a mouse or activates them via the keyboard.
• Richer interfaces − You can use JavaScript to include such items as drag-and-drop
components and sliders to give a Rich Interface to your site visitors.
Limitations of JavaScript
• Client-side JavaScript does not allow the reading or writing of files. This has been kept for
security reason.
1. Install a text editor or IDE: Choose a text editor or IDE that suits your preferences and
install it on your computer. Some popular options include Visual Studio Code, Sublime
Text, Atom, or WebStorm.
2. Install a web browser: JavaScript runs in web browsers, so you need a browser to test
your code. Chrome, Firefox, Safari, and Edge are commonly used browsers for
JavaScript development.
3. Create a project directory: Create a directory on your computer where you'll store your
JavaScript files and other project assets.
4. Create an HTML file: In your project directory, create an HTML file with a .html
extension. This file will serve as the entry point for your JavaScript code.
5. Link your JavaScript file: Within the HTML file, use the <script> tag to link your
JavaScript file. You can either write your JavaScript code directly within
the <script> tags or link an external JavaScript file using the src attribute.
6. Start coding: Open your HTML file in a web browser to see the changes made by your
JavaScript code. You can use the browser's developer tools to debug and inspect your
JavaScript code.
Here, we are going to use JavaScript in developing a web application. So, we must have at
least two things, a browser, and an editor to write the JavaScript code.
Although we also need a webserver to run a web application, but we will use a single HTML
web page to run our JavaScript code. So, no need to install it for now.
Browser
Mostly, you will have a browser already installed on your PC, Microsoft Edge on the
Windows platform, and Safari on Mac OS.
You can also install the following browser as per your preference:
• Microsoft Edge
• Google Chrome
• Mozilla FireFox
• Safari
• Opera
You can write JavaScript code using a simple editor like Notepad. However, you can install
any open-sourced or licensed IDE (Integrated Development Environment) to get the
advantage of IntelliSense support for JavaScript and syntax error/warning highlighter for
rapid development.
Use the online editor to quickly execute the JavaScript code without any installation. The
followings are free online editors:
• [Link]
• [Link]
• [Link]
There are a few ways to insert JavaScript code into an HTML document:
Inline script: You can include JavaScript code directly within the HTML file using
the <script> tag. Place the <script> tag within the <head> or <body> section of the HTML files,
and writes your JavaScript code between the opening <script> and closing </script> tags.
JavaScript string (primitive or String object) includes default properties and methods which
you can use for different purposes.
For example:
The HTML script tag <script> is used to embed data or executable client-side scripting
language in an HTML page. Mostly, JavaScript or JavaScript based API code inside
a <script></script> tag. The following is an example of an HTML page that contains the
JavaScript code in a <script> tag.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1> JavaScript Tutorials</h1>
<script>
//write JavaScript code here.
alert('Hello, how are you?')
</script>
</body>
</html>
In the above example, a <script></script> tag contains the JavaScript alert ('Hello, how are
you?') that display a message box.
HTML v4 requires the type attribute to identify the language of script code embedded within
script tag. This is specified as MIME type e.g. 'text/javascript', 'text/ecmascript',
'text/vbscript', etc.
HTML v5 page does not require the type attribute because the default script language is
'text/javascript' in a <script> tag.
An HTML page can contain multiple <script> tags in the <head> or <body> tag. The browser
executes all the script tags, starting from the first script tag from the beginning.
Scripts without async, defer or type="module" attributes, as well as inline scripts, are fetched
and executed immediately, before the browser continues to parse the page. Consider the
following page with multiple script tags.
<!DOCTYPE html>
<html>
<head>
<script>
alert('Executing JavaScript 1')
</script>
</head>
<body>
<h1> JavaScript Tutorials</h1>
<script>
alert('Executing JavaScript 2')
</script>
<script>
alert('Executing JavaScript 3')
</script>
</body>
</html>
Above, the first <script> tag containing alert ('Executing JavaScript 1') will be executed first,
then alert ('Executing JavaScript 2') will be executed, and then alert('Executing JavaScript
3') will be executed.
The browser loads all the scripts included in the <head> tag before loading and rendering
the <body> tag elements. So, always include JavaScript files/code in the <head> that are going
to be used while rendering the UI. All other scripts should be placed before the
ending </body> tag. This way, you can increase the page loading speed.
A <script> tag can also be used to include an external script file to an HTML web page by
using the src attribute.
If you don't want to write inline JavaScript code in the <script></script> tag, then you can also
write JavaScript code in a separate file with .js extension and include it in a web page using
<script> tag and reference the file via src attribute.
<!DOCTYPE html>
<html>
<head>
<script src="/[Link]" ></script>
</head>
<body>
<h1> JavaScript Tutorials</h1>
</body>
</html>
Above, the <script src="/[Link]"> points to the external JavaScript file using
the src="/[Link]" attribute where the value of the src attribute is the path or url
from which a file needs to be loaded in the browser. Note that you can load the files from
your domain as well as other domains.
Global Attributes
Attribute Usage
async <script async> executes the script asynchronously along with the rest of the
page.
crossorign <script crossorigin="anonymous|use-credentials"> allows error logging for sites
which use a separate domain for static media. Value anonymous do not send
credentials, whereas use-credentials sends the credentials.
defer <script defer> executes the script after the document is parsed and before
firing DOMContentLoaded event.
src <script src="uri\path to resource"> specifies the URI/path of an external script
file;
type <script type="text\javascript"> specifies the type of the containing script e.g.
text\javascript, text\html, text\plain, application\json, application\pdf, etc.
referrerpolicy <script referrerpolicy="no-referrer"> specifies which referrer information to
send when fetching a script. Values can be no-referrer, no-referrer-when-
downgrade, origin, same-origin, strict-origin, etc.
integrity <script integrity="sha384-oqVuAfXRKap7fdgc"> specifies that a user agent can
use to verify that a fetched resource has been delivered free of unexpected
manipulation.
Attribute Usage
nomodule <script nomodule> specifies that the script should not be executed in browsers
supporting ES2015 modules.
By using these methods, you can insert and execute JavaScript code within an HTML document,
allowing you to enhance the functionality and interactivity of your web pages.
Self-check 1-1:
Dear Students! Give brief answer for the following review questions:
Unit Summary
JavaScript's fundamentals include variables, data types, operators, control flow, functions,
objects, arrays, and error handling. You'll use these to manipulate the DOM, handle events, and
even fetch data asynchronously. By mastering these concepts, you'll be able to define and use
functions, including anonymous ones, work with DOM elements dynamically, and handle user
interactions seamlessly.
UNIT 2
INTERACTIVITY USING JAVASCRIPT
Unit Coverage
This unit is designed to provide you the necessary information and practice regarding the
following content coverage:
[Link] syntax and basic concepts
[Link] structures and loops
[Link] in JavaScript
Unit Learning Outcomes
This unit will also assist you to attain the following learning outcomes. Specifically, upon
completion of this unit, you will be able to:
✓ Apply interactivity using JavaScript
JavaScript is the third most important web technology after HTML and CSS. JavaScript can be
used to create web and mobile applications, build web servers, create games, etc.
JavaScript can be used in various activities like data validation, displaying popup messages,
handling events of HTML elements, modifying CSS, etc.
In early 1995, Brendan Eich from Netscape designed and implemented a new language for non-
java programmers to give newly added Java support in Netscape navigator. It was initially
named Mocha, then LiveScript, and finally JavaScript.
As mentioned in the previous chapter, JavaScript code can be written inside HTML Script
Tags or in a separate file with .js extension.
<script>
//Write javascript code here...
</script>
Character Set
JavaScript uses the unicode character set, so allows almost all characters, punctuations, and
symbols.
Case Sensitive
Variables
<script>
var name = "Abebe";
id = 10;
</script>
Semicolon
<script>
var two = 2; three = 3; //three different statements
var four = 4; //single statement
var five = "Five" //single statement without ;
</script>
Whitespaces
JavaScript ignores multiple spaces and tabs. The following statements are the same.
<script>
var > var > var ></script>
Code Comments
A comment is single or multiple lines, which give some information about the current
program. Comments are not for execution.
Write comment after double slashes // or write multiple lines of comments between /* and */
<script>
var // this is a single line comment
/* this
is multi line
comment*/
var two = 2;
var three = 3;
</script>
String
A string is a text in JavaScript. The text content must be enclosed in double or single
quotation marks.
<script>
var msg = "Hello World" //JavaScript string in double quotes
var msg = 'Hello World' //JavaScript string in single quotes
</script>
Number
JavaScript allows you to work with any type of number like integer, float, hexadecimal etc.
Number must NOT be wrapped in quotation marks.
<script>
var num = 100;
var flot = 10.5;
</script>
Boolean
As in other languages, JavaScript also includes true and false as a boolean value.
<script>
Keywords are reserved words in JavaScript, which cannot be used as variable names or
function names.
Var function if
Else do while
In instanceOf typeOf
[Link] Variables
Variable means anything that can vary. In JavaScript, a variable stores data that can be
changed later on.
Declare a Variable
• var keyword is used to declare variables since JavaScript was created. It is confusing
and error-prone when using variables declared using var.
• let keyword removes the confusion and error of var. It is the new and recommended
way of declaring variables in JavaScript.
• const keyword is used to declare a constant variable that cannot be changed once
assigned a value.
Here, we will use the let keyword to declare variables. To declare a variable, write the
keyword let followed by the name of the variable you want to give, as shown below.
You can assign a value to a variable using the = operator when you declare it or after the
declaration and before accessing it.
let msg;
msg = "Hello JavaScript!"; // assigning a string value
In the above example, the msg variable is declared first and then assigned a string value in the
next line.
You can declare a variable and assign a value to it in the same line. Values can be of
any datatype such as string, numeric, boolean, etc.
Dynamic Typing
JavaScript is a loosely typed language. It means that you don't need to specify what data type
a variable will contain. You can update the value of any type after initialization. It is also
called dynamic typing.
Variable Scope
In JavaScript, a variable can be declared either in the global scope or the local scope.
Global Variables
Variables declared out of any function are called global variables. They can be accessed
anywhere in the JavaScript code, even inside any function.
Local Variables
Variables declared inside the function are called local variables of that function. They can
only be accessed in the function where they are declared but not outside.
The variables declared without the var keyword become global variables, irrespective of
where they are declared. Visit Variable Scope in JavaScript to learn about it.
function myfunction(){
msg = "Hello JavaScript!";
}
myfunction();
alert(msg); // msg becomes global variable so can be accessed here
Points to Remember
1. Variables can be defined using let keyword. Variables defined without let or var keyword
become global variables.
2. Variables should be initialized before accessing it. Unassigned variable has value undefined.
4. Variables can have local or global scope. Local variables cannot be accessed out of the function
where they are declared, whereas the global variables can be accessed from anywhere.
[Link] Comments
Single Line Comments
Example
// Change heading:
[Link]("myH").innerHTML = "My First Page";
// Change paragraph:
[Link]("myP").innerHTML = "My first paragraph.";
This example uses a single line comment at the end of each line to explain the code:
Example
This example uses a multi-line comment (a comment block) to explain the code:
Example
/*
The code below will change
the heading with id = "myH"
and the paragraph with id = "myP"
in my web page:
*/
[Link]("myH").innerHTML = "My First Page";
[Link]("myP").innerHTML = "My first paragraph."
Adding // in front of a code line changes the code lines from an executable line to a comment.
Example
Example
/*
[Link]("myH").innerHTML = "My First Page";
[Link]("myP").innerHTML = "My first paragraph.";
*/
[Link] Javascript Operators
JavaScript includes operators same as other languages. An operator performs some operation
on single or multiple operands (data value) and produces a result. For example, in 1 + 2,
the + sign is an operator and 1 is left side operand and 2 is right side operand. The + operator
performs the addition of two numeric values and returns a result. JavaScript includes
following categories of operators.
1. Arithmetic Operators
2. Comparison Operators
3. Logical Operators
4. Assignment Operators
5. Conditional Operators
6. Ternary Operator
Arithmetic Operators
Arithmetic operators are used to perform mathematical operations between numeric operands.
Operator Description
The following example demonstrates how arithmetic operators perform different tasks on
operands.
let x = 5, y = 10;
let z = x + y; //performs addition and returns 15
z = y - x; //performs subtraction and returns 5
z = x * y; //performs multiplication and returns 50
z = y / x; //performs division and returns 2
z = x % 2; //returns division remainder 1
The ++ and -- operators are unary operators. It works with either left or right operand only.
When used with the left operand, e.g., x++, it will increase the value of x when the program
control goes to the next statement. In the same way, when it is used with the right operand,
e.g., ++x, it will increase the value of x there only. Therefore, x++ is called post-increment,
and ++x is called pre-increment.
let x = 5;
x++; //post-increment, x will be 5 here and 6 in the next line
++x; //pre-increment, x will be 7 here
x--; //post-decrement, x will be 7 here and 6 in the next line
--x; //pre-decrement, x will be 5 here
String Concatenation
The + operator performs concatenation operation when one of the operands is of string type.
The following example demonstrates string concatenation even if one of the operands is a
string.
JavaScript provides comparison operators that compare two operands and return a boolean
value true or false.
Operators Description
Operators Description
> Returns a boolean value true if the left-side value is greater than the right-side value;
otherwise, returns false.
< Returns a boolean value true if the left-side value is less than the right-side value;
otherwise, returns false.
>= Returns a boolean value true if the left-side value is greater than or equal to the right-
side value; otherwise, returns false.
<= Returns a boolean value true if the left-side value is less than or equal to the right-side
value; otherwise, returns false.
In JavaScript, the logical operators are used to combine two or more conditions. JavaScript
provides the following logical operators.
Operator Description
&& && is known as AND operator. It checks whether two operands are non-zero or not
(0, false, undefined, null or "" are considered as zero). It returns 1 if they are non-
zero; otherwise, returns 0.
|| || is known as OR operator. It checks whether any one of the two operands is non-
zero or not (0, false, undefined, null or "" is considered as zero). It returns 1 if any
one of of them is non-zero; otherwise, returns 0.
! ! is known as NOT operator. It reverses the boolean result of the operand (or
condition). !false returns true, and !true returns false.
let a = 5, b = 10;
(a != b) && (a < b); // returns true
(a > b) || (a == b); // returns false
(a < b) || (a == b); // returns true
!(a < b); // returns false
!(a > b); // returns true
Assignment Operators
JavaScript provides the assignment operators to assign values to variables with less key
strokes.
Assignment Description
operators
+= Sums up left and right operand values and assigns the result to the left
operand.
-= Subtract right operand value from the left operand value and assigns the
result to the left operand.
*= Multiply left and right operand values and assigns the result to the left
operand.
/= Divide left operand value by right operand value and assign the result to the
left operand.
%= Get the modulus of left operand divide by right operand and assign resulted
modulus to the left operand.
JavaScript provides a special operator called ternary operator :? that assigns a value to a
variable based on some condition. This is the short form of the if else condition.
Syntax:
let a = 10, b = 5;
1. JavaScript includes operators that perform some operation on single or multiple operands (data
value) and produce a result.
JavaScript includes primitive and non-primitive data types as per the latest ECMAScript 5.1
specification.
The primitive data types are the lowest level of the data value in JavaScript. The followings
are primitive data types in JavaScript:
String String is a textual content wrapped inside ' ' or " " or ` ` (tick sign).
Example: 'Hello World!', "This is a string", etc.
Boolean Boolean is a logical data type that has only two values, true or false.
Undefined undefined is the default value of a variable that has not been assigned any
value.
Example: In the variable declaration, var str;, there is no value assigned to str.
So, the type of str can be check using typeof(str) which will return undefined.
The structural data types contain some kind of structure with primitive data.
Example:
let person = {
firstName: "Aster",
lastName: "Aweke",
age: 15
};
Date The Date object represents date & time including days, months, years,
hours, minutes, seconds, and milliseconds.
Example: let today = new Date("25 July 2021");
Example
let x, y, z; // Statement 1
x = 5; // Statement 2
y = 6; // Statement 3
z = x + y; // Statement 4
JavaScript Programs
JavaScript Statements
This statement tells the browser to write "Hello Dolly." inside an HTML element with
id="demo":
Example
The statements are executed, one by one, in the same order as they are written.
JavaScript programs (and JavaScript statements) are often called JavaScript code.
Semicolons;
Examples
a = 5; b = 6; c = a + b;
JavaScript ignores multiple spaces. You can add white space to your script to make it more
readable.
let x = y + z;
JavaScript includes if/else conditional statements to control the program flow, similar to other
programming languages.
1. if Statement
2. if else Statement
3. else if Statement
if Statement
Use if conditional statement if you want to execute something based on some condition.
if(boolean expression)
{
// code to be executed if condition is true
}
Example: if condition
if( 1 > 0)
{
alert("1 is greater than 0");
}
if( 1 < 0)
{
alert("1 is less than 0");
}
In the above example, the first if statement contains 1 > 0 as conditional expression. The
conditional expression 1 > 0 will be evaluated to true, so an alert message "1 is greater than 0"
will be displayed, whereas conditional expression in second if statement will be evaluated to
false, so "1 is less than 0" alert message will not be displayed.
Example: if condition
Note:
curly braces { } is not required when if block contains only a single line to execute.
Use comparison operators carefully when writing conditional expression. For example, ==
and === is different.
Example: if condition
if(1=="1")
{
alert("== operator does not consider types of operands");
}
if(1==="1")
{
alert("=== operator considers types of operands");
}
else condition
Use else statement when you want to execute the code every time when if condition evaluates
to false.
The else statement must follow if or else if statement. Multiple else block is NOT allowed.
if(condition expression)
{
//Execute this code..
}
else{
//Execute this code..
}
Example: else condition
Use "else if" condition when you want to apply second level condition after if statement.
if(condition expression)
{
//Execute this code block
}
else if(condition expression){
//Execute this code block
}
Example: else if condition
Remember:
2. JavaScript includes three forms of if condition: if condition, if else condition and else if
condition.
615
Student Module
3. The if condition must have conditional expression in brackets () followed by single statement or
code block wrapped with { }.
4. 'else if' statement must be placed after if condition. It can be used multiple times.
5. 'else' condition must be placed only once at the end. It must come after if or else if statement.
JavaScript includes for loop like Java or C#. Use for loop to execute code repeatedly.
616
Student Module
The for loop can also be used to get the values for an array.
617
Student Module
Remember:
1. JavaScript for loop is used to execute code repeatedly.
2. for loop includes three parts: initialization, condition and iteration. [Link](initializer; condition;
iteration){ ... }
4. An initializer can be specified before starting for loop. The condition and increment statements
can be included inside the block.
For best readability, programmers often like to avoid code lines longer than 80 characters.
If a JavaScript statement does not fit on one line, the best place to break it is after an operator:
Example
[Link]("demo").innerHTML =
"Hello Dolly!";
JavaScript statements can be grouped together in code blocks, inside curly brackets {...}.
One place you will find statements grouped together in blocks, is in JavaScript functions:
618
Student Module
Example
function myFunction() {
[Link]("demo1").innerHTML = "Hello Dolly!";
[Link]("demo2").innerHTML = "How are you?";
}
In this tutorial we use 2 spaces of indentation for code blocks.
You will learn more about functions later in this tutorial.
JavaScript is a loosely-typed language. It does not give compile-time errors. So some times
you will get a runtime error for accessing an undefined variable or calling undefined function
etc.
try
{
// code that may throw an error
}
catch(ex)
{
// code to be executed if an error occurs
}
finally{
// code to be executed regardless of an error occurs or not
}
• Catch: write code to do something in catch block when an error occurs. The catch block
can have parameters that will give you error information. Generally catch block is used to
log an error or display specific messages to the user.
• Finally: code in the finally block will always be executed regardless of the occurrence of
an error. The finally block can be used to complete the remaining task or reset variables
that might have changed before error occurred in try block.
try
{
var result = Sum(10, 20); // Sum is not defined yet
}
catch(ex)
{
[Link]("errorMessage").innerHTML = ex;
}
In the above example, we are calling function Sum, which is not defined yet. So, try block
will throw an error which will be handled by catch block. Ex includes error message that can
be displayed.
620
Student Module
try
{
var result = Sum(10, 20); // Sum is not defined yet
}
catch(ex)
{
[Link]("errorMessage").innerHTML = ex;
}
finally{
[Link]("message").innerHTML = "finally block executed";
}
Throw
try
{
throw "Error occurred";
}
catch(ex)
{
alert(ex);
}
You can use JavaScript object for more information about an error.
try
{
throw {
number: 101,
message: "Error occurred"
};
}
catch (ex) {
alert([Link] + "- " + [Link]);
}
Functions are the basic building block of JavaScript. Functions allow us to encapsulate a
block of code and reuse it multiple times.
JavaScript Keywords
JavaScript statements often start with a keyword to identify the JavaScript action to be
performed.
Keyword Description
Var Declares a variable
Functions make JavaScript code more readable, organized, reusable, and maintainable.
The following defines a function named greet that will display an alert box.
function greet() {
alert("Hello World!");
}
The above greet() function does not include any input parameters. It contains a single statement
that displays an alert message.
Now, you can call or invoke the greet function by using the function name followed by
the () operator, as shown below. When you call a function, JavaScript will execute the codes
written inside the calling function.
greet ();
2.4.2 Function Expressions and Anonymous Functions:
Create functions on the fly using function expressions. Utilize anonymous functions for concise
code and event handling.
A function expression in JavaScript is a function that is stored as a value, and can be assigned
to a variable or passed as an argument to another function.
In JavaScript, you can also create anonymous functions, which are functions without a name.
Anonymous functions are often used as arguments to other functions, and are
Anonymous functions are typically used in functional programming e.g. callback function,
creating closure or immediately invoked function expression.
Arrow functions are a shorthand syntax for defining anonymous functions in JavaScript. They
have compact syntax compared to anonymous functions. However, they do not have their
own this value.
In JavaScript, a function can have one or more inner functions. These nested functions are in
the scope of outer function. Inner function can access variables and parameters of outer
function. However, outer function cannot access variables defined inside inner functions.
function greet(firstName)
{
function SayHello() {
alert("Hello " + firstName);
}
return SayHello();
}
greet("Abebe");
2.4.3 Arrow Functions and Their Syntax:
Learn the modern, concise syntax of arrow functions and their benefits.
Before Arrow:
hello = function() {
return "Hello World!";
}
hello = () => {
return "Hello World!";
}
It gets shorter! If the function has only one statement, and the statement returns a value, you can
remove the brackets and the return keyword:
Note: This works only if the function has only one statement.
In fact, if you have only one parameter, you can skip the parentheses as well:
Let us take a look at two examples to understand the difference. Both examples call a method
twice, first when the page loads, and once again when the user clicks a button.
The first example uses a regular function, and the second example uses an arrow function.
The result shows that the first example returns two different objects (window and button), and
the second example returns the window object twice, because the window object is the "owner"
of the function.
Example
With a regular function this represents the object that calls the function:
// Regular Function:
hello = function() {
[Link]("demo").innerHTML += this;
}
// The window object calls the function:
[Link]("load", hello);
// A button object calls the function:
[Link]("btn").addEventListener("click", hello);
Example
// Arrow Function:
hello = () => {
[Link]("demo").innerHTML += this;
}
// The window object calls the function:
[Link]("load", hello);
// A button object calls the function:
[Link]("btn").addEventListener("click", hello);
Remember these differences when you are working with functions. Sometimes the behavior of
regular functions is what you want, if not, use arrow functions.
You can pass values to a function using parameters. A function can have one or more
parameters, and the values will be passed by the calling code.
A function can return a value to the calling code using the return keyword followed by a
variable or a value.
function getNumber() {
return 10;
};
let result = getNumber();
[Link](result); //output: 10
Typically, a function returns some calculated value using paramters or an expression from a
function. For example, the following sum function adds two parameters values using
the + operator and returns the result of an expression.
function multiple(x) {
function fn(y)
{
return x * y;
}
return fn;
}
var triple = multiple(3);
triple(2); // returns 6
triple(3); // returns 9
In JavaScript, a string is a primitive data type that is used for textual data. JavaScript string
must be enclosed in single quotes, double quotes, or backticks. The followings are string
literals in JavaScript.
"Hello World"
'Hello World'
`Hello World`
The string literal can be assigned to a variable using the equal to = operator.
You can include single quotes in double-quoted string or include double quotes in a single
quoted string. However, you cannot include a single quote in single quoted string and double
quotes in double-quoted string.
String Concatenation
JavaScript allows you to create a string object using the new keyword, as shown below.
Two strings can be compared using <, >, ==, === operator,
and [Link](string) method.
The mathematical operators < and > compare two strings and return a boolean (true or false)
based on the order of the characters in the string.
The == operator compares the content of strings and === compares the reference equality of
strings. The localeCompare() method compares two strings in the current locale. It returns 0 if
strings are equal, else returns 1.
JavaScript comments can be used to explain JavaScript code, and to make it more readable.
JavaScript comments can also be used to prevent execution, when testing alternative code.
We have learned that a variable can hold only one value. We cannot assign multiple values to
a single variable. JavaScript array is a special type of variable, which can store multiple
values using a special syntax.
Another way of creating arrays is using the Array() constructor, as shown below.
The following are some more examples of arrays that store different types of data.
Use the length property to get the total number of elements in an array. It changes as and when
you add or remove elements from the array.
You can update the elements of an array at a particular index using arrayName[index] =
new_value syntax.
You can add new elements using arrayName[index] = new_value syntax. Just make sure that
the index is greater than the last index. If you specify an existing index then it will update the
value.
The recommended way of adding elements at the end is using the push() method. It adds an
element at the end of an array.
The pop() method returns the last element and removes it from the array.
You cannot remove middle elements from an array. You will have to create a new array from
an existing array without the element you do not want, as shown below.
>
In this example, the content of the <h1> element is changed when a user clicks on it:
Example
<!DOCTYPE html>
<html>
<body>
<h1 = 'Ooops!'">Click on this text!</h1>
</body>
</html>
Example
<!DOCTYPE html>
<html>
<body>
<h1 on this text!</h1>
<script>
function changeText(id) {
[Link] = "Ooops!";
}
</script>
</body>
</html>
Example
In the example above, a function named displayDate will be executed when the button is clicked.
The HTML DOM allows you to assign events to HTML elements using JavaScript:
Example
<script>
[Link]("myBtn"). ></script>
In the example above, a function named displayDate is assigned to an HTML element with
the id="myBtn". The function will be executed when the button is clicked.
The onload and onunload events are triggered when the user enters or leaves the page.
The onload event can be used to check the visitor's browser type and browser version, and load
the proper version of the web page based on the information.
The onload and onunload events can be used to deal with cookies.
Example
<body >
The oninput event is often to some action while the user input data. Below is an example of how
to use the oninput to change the content of an input field.
Example
The onchange event is often used in combination with validation of input fields. Below is an
example of how to use the onchange. The upperCase() function will be called when a user changes
the content of an input field.
Example
<input type="text" id="fname" >
Self-check 2-1:
Unit Summary
Unit Two focuses on applying interactivity to web pages using JavaScript. It covers essential
concepts and techniques that enable trainees to enhance user experience and add dynamic
functionality to their web applications. The unit covers the following content:
• JavaScript syntax and basic concepts: Trainees learn the fundamentals of JavaScript
syntax, including variables, data types, operators, and control structures like conditionals
and loops.
• Control structures and loops: Trainees explore different control structures, such as if-else
statements and switch statements, and learn how to use loops like for, while, and do-
while to control program flow.
• Functions in JavaScript: Trainees gain knowledge of defining and invoking functions,
understanding function expressions and anonymous functions, and working with
parameters, arguments, and default values.
• DOM manipulation and event handling: Trainees delve into the Document Object Model
(DOM) and learn how to access and modify DOM elements using JavaScript. They also
discover how to dynamically add and remove elements. Additionally, trainees gain an
understanding of event handling and event propagation, enabling them to create
interactive features.
Here are some overview questions for Unit Two: Apply Interactivity Using JavaScript:
1. What is the syntax of JavaScript, and what are some basic concepts that you should be
familiar with?
2. How do control structures and loops work in JavaScript, and what are their uses?
3. What are functions in JavaScript, and how do you define and invoke them?
4. Explain function expressions and anonymous functions in JavaScript.
5. What are parameters, arguments, and default values in JavaScript functions?
6. What is the Document Object Model (DOM) in JavaScript, and how does it relate to web
page elements?
7. How do you access and modify DOM elements using JavaScript?
8. Can you explain how to dynamically add and remove elements in the DOM using
JavaScript?
9. What is event handling in JavaScript, and how does it facilitate interactivity?
10. How does event propagation work in JavaScript, and what are its implications for
handling events?
Multiple choice
1. What are the topics covered in the unit related to JavaScript syntax and basic concepts?
a) Variables, data types, and operators
b) Statements, expressions, and comments
c) Type conversions
d) All of the above
UNIT 3
VALIDATING USER INPUT
Unit Coverage
This unit is designed to provide you the necessary information and practice regarding the
following content coverage:
[Link]
Validation is the process of checking if user input conforms to specific rules or constraints.
• It helps ensure that the data entered is accurate, complete, and appropriate for the
intended purpose.
• Validation can be performed on various types of user input, such as text fields,
checkboxes, radio buttons, dropdowns, and file uploads.
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required>
In this example, we have a simple form with three fields: name, email, and password. The
"required" attribute is added to ensure that these fields are mandatory.
2. JavaScript Validation:
Javascript
[Link]("submit", function(event) {
if (![Link]()) {
[Link](); // Prevent form submission if validation fails
}
});
In this JavaScript code, we get a reference to the form element using its ID. We then add an
event listener for the form's "submit" event. Inside the event handler function, we check if the
form is valid using the checkValidity() method. If the form is not valid, we
use [Link]() to prevent the form submission.
With this setup, HTML5's built-in form validation will handle basic validation, such as checking
if required fields are filled and if the email field has a valid email format. Additionally, you can
use JavaScript to implement custom validation logic by checking specific conditions or patterns
using regular expressions or other techniques.
It's important to note that HTML5 form validation provides a convenient way to perform basic
client-side validation. However, server-side validation should always be implemented to ensure
data integrity and security.
<label for="password">Password:</label>
<input type="password" id="password" name="password" required minlength="6">
Self-check 3-1:
Unit Summary
Form validation is a critical process in web application development that ensures user input
meets specific criteria before processing or storing it. By validating user input, developers can
improve data accuracy, prevent errors, enhance security, and provide a better user experience.
Form validation can be performed using client-side or server-side techniques, or a combination
of both. Client-side validation, carried out using JavaScript or HTML5 validation attributes,
provides immediate feedback to users. Server-side validation, performed on the server after form
submission, offers a more robust and secures validation process.
Common validation techniques include checking for required fields, validating data formats,
ensuring numeric or alphanumeric inputs, and implementing custom validation based on business
rules. Trainees should understand the importance of form validation, potential security concerns,
and various validation techniques to effectively implement validation in web applications.
Project work
Project Overview: first select one organization and based on business logic, Develop an
interactive website for students that provides a user-friendly interface, helpful resources, and
interactive features to enhance their learning experience. Task should perform as follows:
1. Requirements Gathering: Identify the required features and functionalities.
2. Planning and Design: Create a simple sitemap to outline the website's structure and
navigation and planning
3. Development: including both back end and front end
4. Testing and Quality Assurance: Conduct testing to ensure the website functions correctly
across different browsers and devices. Verify that interactive features, forms, and data
submission work properly. Address any bugs or errors discovered during testing.
RB: Students should submit and present for the class and graded after completing Grade 11
courses
• JavaScript is primarily used for scripting web pages and runs on the client side within a
web browser. It's known for its asynchronous programming model, which allows for
dynamic updates without reloading the entire page. Unlike languages like Java or Python,
JavaScript's syntax and execution model are tailored for manipulating web page elements
and handling events.
2. Variables in JavaScript:
• Variables in JavaScript are containers for storing data values. They are declared using
var, let, or const keywords followed by the variable name. Example:
javascript
Copy code
// Using var
var count = 10;
• JavaScript can be included in HTML files using the <script> tag. It can be placed in the
<head> or <body> section of the HTML document. Example:
html
Copy code
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Example</title>
<script src="[Link]"></script> <!-- External JavaScript file -->
</head>
<body>
<h1>Hello, world!</h1>
<script>
// Inline JavaScript code
[Link]('This is inline JavaScript');
</script>
</body>
</html>
• JavaScript can also be embedded directly within HTML using <script> tags, either inline
or by linking to an external .js file using the src attribute.
javascript
Copy code
// Using var
var age = 30;
3. JavaScript operators:
o Arithmetic operators: + (addition), - (subtraction), * (multiplication), /
(division), % (remainder).
o Comparison operators: == (equal to), != (not equal to), === (strict equal to),
!== (strict not equal to), > (greater than), < (less than), >= (greater than or equal
to), <= (less than or equal to).
o Logical operators: && (logical AND), || (logical OR), ! (logical NOT).
javascript
Copy code
// Examples
let x = 5;
let y = 3;
// Arithmetic
let sum = x + y; // 8
// Comparison
[Link](x > y); // true
// Logical
let condition = (x > 0) && (y < 0); // false
javascript
Copy code
let num = 10;
if (num > 0) {
[Link]('Number is positive');
5. Function in JavaScript:
o A function in JavaScript is a block of reusable code designed to perform a
particular task.
6. Declaring a function in JavaScript:
o Function Declaration:
javascript
Copy code
function greet(name) {
[Link](`Hello, ${name}!`);
}
greet('Alice'); // Hello, Alice!
o Function Expression:
javascript
Copy code
let square = function(x) {
return x * x;
};
[Link](square(5)); // 25
javascript
Copy code
function add(a, b) { // a and b are parameters
return a + b;
}
• Form validation ensures that user input submitted through web forms is correct,
complete, and meets specified criteria before it is processed or sent to a server. It helps
prevent erroneous or malicious data from being submitted, improves data quality, and
enhances user experience by providing feedback to users on how to correct input errors.
• Client-side validation: Validation that occurs in the user's browser using JavaScript or
HTML5 attributes. It provides immediate feedback to users but can be bypassed or
manipulated by users.
• Server-side validation: Validation that occurs on the server after the form data has been
submitted. It ensures data integrity and security, as it cannot be bypassed by users.