[Go to site: main page, start]

0% found this document useful (0 votes)
12 views93 pages

Grade 11 Web JavaScript

The document is a module for Grade 11 Web Design and Development focused on applying interactivity to websites using JavaScript. It covers scripting languages, JavaScript basics, and user input validation, providing learning outcomes, instructions, and practical activities for students. Key topics include JavaScript features, applications, advantages, limitations, and setting up a development environment.

Uploaded by

edensam951
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views93 pages

Grade 11 Web JavaScript

The document is a module for Grade 11 Web Design and Development focused on applying interactivity to websites using JavaScript. It covers scripting languages, JavaScript basics, and user input validation, providing learning outcomes, instructions, and practical activities for students. Key topics include JavaScript features, applications, advantages, limitations, and setting up a development environment.

Uploaded by

edensam951
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Module VI

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:

Learning Instructions: How to use this Module

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.

Ministry of Education 572


Grade 11 Web Design and Development Student 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)

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:
✓ Identify scripting language

Key Terms: JavaScript, syntax, DOM, loops.

1.1 Identify scripting language


To identify a scripting language, you can look for certain characteristics and features that are
commonly associated with scripting languages. Here are a few key indicators:
1. Interpreted execution: Scripting languages are typically interpreted rather than compiled,
meaning the code is executed by an interpreter at runtime rather than being compiled into
machine code beforehand.
2. High-level syntax: Scripting languages often have a simplified and high-level syntax that
is easy to read and write, making them accessible to non-programmers and beginners.
3. Dynamic typing: Scripting languages usually employ dynamic typing, which means you
don't need to explicitly declare variable types. Variables can change their type during
runtime.
4. Built-in libraries and frameworks: Scripting languages often provide extensive libraries
and frameworks that make it easier to perform common tasks and interact with various
system resources or APIs.

Ministry of Education 573


Grade 11 Web Design and Development Student Module

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.

1.2. Introduction to JavaScript (JS)


By applying interactivity to a website, you can make it more engaging, user-friendly, and
interactive, leading to improved user satisfaction and increased user interaction with the
website's content.
"Apply interactivity to a website" refers to the process of adding dynamic and interactive
elements to a website to enhance the user experience and engage the visitors. It involves using
programming languages like JavaScript to create interactive features, handle user interactions,
and manipulate the content of the webpage in real-time.
When a website is interactive, it allows users to actively engage with the content, perform
actions, and receive immediate feedback.
1.2.1. Preface of JavaScript:
JavaScript is a high-level, interpreted programming language that was initially created to add
interactivity to web pages. It was developed by Brendan Eich in 1995 and has since become
one of the most widely used languages for web development. JavaScript allows developers to
add functionality to web pages, manipulate the Document Object Model (DOM), and create
responsive user interfaces. Unlike HTML and CSS, which focus on structure and styling,
JavaScript is a scripting language that enables client-side scripting, making web pages more
dynamic.

Ministry of Education 574


Grade 11 Web Design and Development Student Module

1.2.2. Role of JavaScript in web development:


JavaScript plays a vital role in web development by enabling dynamic and interactive features on
web pages. It runs on the client-side, meaning it executes within the user's web browser,
allowing it to manipulate the Document Object Model (DOM) and respond to user interactions.
JavaScript is used to enhance user experience, validate form inputs, create interactive elements,
handle events, fetch and display data from APIs, and perform various other tasks that make
websites more engaging and user-friendly.

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.

Ministry of Education 575


Grade 11 Web Design and Development Student Module

• 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.

Fig: 1.1.1. Java Script Features

Ministry of Education 576


Grade 11 Web Design and Development Student Module

1. Object-Centered Script Language

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.

Use of Polymorphism within object-oriented programming requires whenever we use to


represent reference of the parent class to an object of a child class.

2. Client Edge Technology

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.

3. Validation of User’s Input

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.

4. Else and IF Statement

IF and Else Statements are used to perform logical operations.

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.

Ministry of Education 577


Grade 11 Web Design and Development Student Module

6. Ability to Perform in Build Function

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.

7. Case Sensitive Format

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.

8. Light Weight and delicate

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.

10. Handling Events

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.

Some of its notable features include:

a. Interactivity: JavaScript allows developers to add interactivity to websites, enabling


users to interact with elements, perform actions, and receive immediate feedback.

Ministry of Education 578


Grade 11 Web Design and Development Student Module

b. DOM Manipulation: JavaScript provides methods to access and manipulate the


DOM, allowing developers to dynamically modify the content, style, and structure of
web pages.
c. Event Handling: JavaScript can handle various user events, such as button clicks, form
submissions, mouse movements, or keyboard interactions, and execute specific actions in
response.
d. Asynchronous Programming: JavaScript supports asynchronous operations, enabling
developers to perform tasks such as making HTTP requests to APIs and updating web
page content without blocking the execution of other code.
e. Cross-Browser Compatibility: JavaScript is supported by all major web browsers,
ensuring broad compatibility and consistent behavior across different environments.
f. Extensibility: JavaScript can be extended through the use of libraries and frameworks,
providing additional functionality and simplifying common web development tasks.
g. Dynamic Typing: JavaScript uses dynamic typing, allowing variables to change data
types during runtime, providing flexibility and ease of use.
These features, among others, contribute to JavaScript's popularity and its ability to
create interactive and dynamic web experiences.
1.2.4. Application of JavaScript:

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.

Ministry of Education 579


Grade 11 Web Design and Development Student Module

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

The merits of using JavaScript are

• 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

We cannot treat JavaScript as a full-fledged programming language. It lacks the following


important features −

• Client-side JavaScript does not allow the reading or writing of files. This has been kept for
security reason.

Ministry of Education 580


Grade 11 Web Design and Development Student Module

• JavaScript doesn't have any multi-threading or multiprocessor capabilities.


• Once again, JavaScript is a lightweight, interpreted programming language that allows you to
build interactivity into otherwise static HTML pages.
1.2.5. Setting up the JavaScript development environment:

To set up a JavaScript development environment, you need a text editor or an Integrated


Development Environment (IDE) and a web browser. Here are the basic steps:

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.

Ministry of Education 581


Grade 11 Web Design and Development Student Module

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

IDEs for JavaScript Application Development

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.

The followings are some of the well-known JavaScript editors:

• Visual Studio Code (Free, cross-platform)


• Eclipse (Free, cross-platform)
• Atom (Free, cross-platform)
• Notepad++ (Free, Windows)
• Code Lobster (Free, cross-platform)
• WebStorm (Paid, cross-platform)

Online Editors for JavaScript

Use the online editor to quickly execute the JavaScript code without any installation. The
followings are free online editors:

• [Link]
• [Link]
• [Link]

Ministry of Education 582


Grade 11 Web Design and Development Student Module

1.2.6. Method to insert scripts in HTML document:

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.

Example: JavaScript 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.

Ministry of Education 583


Grade 11 Web Design and Development Student Module

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.

Example: 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>

<p>This page contains multiple script tags.</p>

Ministry of Education 584


Grade 11 Web Design and Development Student Module

<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.

Reference the External Script File

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.

Example: JavaScript in a <script> Tag

<!DOCTYPE html>
<html>
<head>
<script src="/[Link]" ></script>
</head>
<body>
<h1> JavaScript Tutorials</h1>

Ministry of Education 585


Grade 11 Web Design and Development Student Module

</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

The <script> can contain the following 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.

Ministry of Education 586


Grade 11 Web Design and Development Student Module

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:

1. What distinguishes JavaScript from other programming languages?


2. What are variables and how are they declared in JavaScript?
3. How is JavaScript included in HTML files?

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.

Ministry of Education 587


Grade 11 Web Design and Development Student Module

Unit Review Questions


Identify Scripting Language
Multiple Choices

1. Which scripting language is introduced in the unit?


a) HTML
b) CSS
c) JavaScript (JS)
d) Python
2. What is the role of JavaScript in web development?
a) Styling web pages
b) Adding interactivity and dynamic behavior
c) Structuring web content
d) Managing databases
3. What are some features of JavaScript?
a) Cascading styles and animations
b) Modular programming and code reusability
c) Dynamic content manipulation and event handling
d) Database management and querying
4. What is the application of JavaScript?
a) Creating server-side applications
b) Writing operating system scripts
c) Developing mobile applications
d) Adding interactivity to web pages
5. How can you set up the JavaScript development environment?
a) By installing a web browser
b) By using a code editor with JavaScript support
c) By configuring server-side settings
d) By adding JavaScript libraries to the website

Ministry of Education 588


Grade 11 Web Design and Development Student Module

6. What is the method to insert JavaScript scripts in an HTML document?


a) Using the <style> tag
b) Using the <script> tag
c) Using the <link> tag
d) Using the <body> tag

Ministry of Education 589


Grade 11 Web Design and Development Student Module

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

Key Terms: JavaScript, structures, loops and Functions.

2.1 Overview of interactivity using JavaScript


JavaScript is a programming language that executes on the browser. It turns static HTML web
pages into interactive web pages by dynamically updating content, validating form data,
controlling multimedia, animate images, and almost everything else on the web pages.

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.

Ministry of Education 590


Grade 11 Web Design and Development Student Module

2.2 JavaScript Syntax and Basic Concepts


Nowadays, JavaScript can execute not only on browsers but also on the server or any device with
a JavaScript Engine. For example, [Link] is a framework based on JavaScript that executes on
the server.

Learn some important characteristics of JavaScript syntax in this section.

As mentioned in the previous chapter, JavaScript code can be written inside HTML Script
Tags or in a separate file with .js extension.

Write JavaScript Code

<script>
//Write javascript code here...
</script>
Character Set

JavaScript uses the unicode character set, so allows almost all characters, punctuations, and
symbols.

Case Sensitive

JavaScript is a case-sensitive scripting language. So, name of functions, variables and


keywords are case sensitive. For example, myfunction and MyFunction are different, Name is
not equal to nAme, etc.

Variables

In JavaScript, a variable is declared with or without the var keyword.

Example: JavaScript Statements

<script>
var name = "Abebe";
id = 10;

Ministry of Education 591


Grade 11 Web Design and Development Student Module

</script>
Semicolon

JavaScript statements are separated by a semicolon. However, it is not mandatory to end a


statement with a semicolon, but it is recommended.

Example: JavaScript Statements

<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.

Example: Whitespaces in JavaScript

<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 */

Example: Comment JavaScript Code

<script>
var // this is a single line comment

Ministry of Education 592


Grade 11 Web Design and Development Student Module

/* 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.

Example: String in JavaScript

<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.

Example: Numbers in JavaScript

<script>
var num = 100;
var flot = 10.5;
</script>
Boolean

As in other languages, JavaScript also includes true and false as a boolean value.

Example: Booleans in JavaScript

<script>

Ministry of Education 593


Grade 11 Web Design and Development Student Module

var yes = true;


var no = false;
</script>
Keywords

Keywords are reserved words in JavaScript, which cannot be used as variable names or
function names.

The following table lists some of the keywords used in JavaScript.

JavaScript Reserved Keywords

Var function if

Else do while

For switch break

Continue return try

Catch finally debugger

Case class this

Default false true

In instanceOf typeOf

New null throw

Void width delete

2.2.1 Variables, Data Types, and Operators:


Understand how to declare and use variables of different data types (numbers, strings, booleans,
objects, arrays). Master various operators for performing calculations, comparisons, and logical
operations.

Ministry of Education 594


Grade 11 Web Design and Development Student Module

[Link] Variables
Variable means anything that can vary. In JavaScript, a variable stores data that can be
changed later on.

Declare a Variable

In JavaScript, a variable can be declared using var, let, const keywords.

• 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.

Example: Variable Declaration

let msg; // declaring a variable without assigning a value


In the above example, var msg; is a variable declaration. It does not have any value yet. The
default value of variables that do not have any value is undefined.

You can assign a value to a variable using the = operator when you declare it or after the
declaration and before accessing it.

Example: Variable Initialization

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.

Ministry of Education 595


Grade 11 Web Design and Development Student Module

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.

Example: Variable Declaration and Initialization

let name = "Abebe"; //assigned string value


let num = 100; //assigned numeric value
let isActive = true; //assigned boolean value
Multiple variables can be declared in a single line, as shown below.

Example: Multiple Variables

let name = "Abebe", num = 100, isActive = true;


You can copy the value of one variable to another variable, as shown below.

Example: Copy Variable

let num1 = 100;


let num2 = num1;
JavaScript allows multiple white spaces and line breaks when you declare a variables.

Example: Whitespace and Line Breaks

let name = "Abebe",


num = 100,
isActive = true;
Variable names are case-sensitive in JavaScript. You cannot declare a duplicate variable using
the let keyword with the same name and case. JavaScript will throw a syntax error. Although,
variables can have the same name if declared with the var keyword (this is why it is
recommended to use let).

Example: Syntax Error

let num = 100;


let num = 200; //syntax error

Ministry of Education 596


Grade 11 Web Design and Development Student Module

var num = 100;


var num = 200; //Ok
JavaScript Variable Nameing Conventions
• Variable names are case-sensitive in JavaScript. So, the variable
names msg, MSG, Msg, mSg are considered separate variables.
• Variable names can contain letters, digits, or the symbols $ and _.
• A variable name cannot start with a digit 0-9.
• A variable name cannot be a reserved keyword in JavaScript, e.g. var, function, return
cannot be variable names.

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.

Example: Loosely Typed Variable

let myvariable = 1; // numeric value


myvariable = 'one'; // string value
myvariable = 1.1; // decimal value
myvariable = true; // Boolean value
myvariable = null; // null value
Constant Variables in JavaScript
Use const keyword to declare a constant variable in JavaScript.

• Constant variables must be declared and initialized at the same time.


• The value of the constant variables can't be changed after initialized them.

Example: Constant Variables


const num = 100;
num = 200; //error

Ministry of Education 597


Grade 11 Web Design and Development Student Module

const name; //error


name = "Abebe";
The value of a constant variable cannot be changed but the content of the value can be
changed. For example, if an object is assigned to a const variable then the underlying value of
an object can be changed.

Example: Constant Variables

const person = { name: 'Abebe'};


[Link] = "Bill";
alert([Link]); //Bill
It is best practice to give constant variable names in capital letters to separate them from other
non-constant variables.

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 following example includes global and local variables.

Example: Global and Local Variable

let greet = "Hello " // global variable


function myfunction(){
let msg = "JavaScript!";

Ministry of Education 598


Grade 11 Web Design and Development Student Module

alert(greet + msg); //can access global and local variable


}
myfunction();
alert(greet);//can access global variable
alert(msg); //error: can't access local variable
Learn global and local scope in JavaScript for more information.

Declare Variables without var and let Keywords


Variables can be declared and initialized without the var or let keywords. However, a value
must be assigned to a variable declared without the var keyword.

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.

It is recommended to declare variable using the let keyword.

Example: Variable Declaration Without var or let Keyword

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.

3. JavaScript is a loosely-typed language, so a variable can store any type value.

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.

Ministry of Education 599


Grade 11 Web Design and Development Student Module

[Link] Comments
Single Line Comments

• Single line comments start with //.


• Any text between // and the end of the line will be ignored by JavaScript (will not be
executed).

This example uses a single-line comment before each code line:

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

let x = 5; // Declare x, give it the value of 5


let y = x + 2; // Declare y, give it the value of x + 2
Multi-line Comments

• Multi-line comments start with /* and end with */.


• Any text between /* and */ will be ignored by JavaScript.

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"

Ministry of Education 600


Grade 11 Web Design and Development Student Module

in my web page:
*/
[Link]("myH").innerHTML = "My First Page";
[Link]("myP").innerHTML = "My first paragraph."

Using Comments to Prevent Execution

Using comments to prevent execution of code is suitable for code testing.

Adding // in front of a code line changes the code lines from an executable line to a comment.

This example uses // to prevent execution of one of the code lines:

Example

//[Link]("myH").innerHTML = "My First Page";


[Link]("myP").innerHTML = "My first paragraph.";
This example uses a comment block to prevent execution of multiple lines:

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

Ministry of Education 601


Grade 11 Web Design and Development Student Module

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

+ Adds two numeric operands.

- Subtract right operand from left operand

* Multiply two numeric operands.

/ Divide left operand by right operand.

% Modulus operator. Returns remainder of two operands.

++ Increment operator. Increase operand value by one.

-- Decrement operator. Decrease value by one.

The following example demonstrates how arithmetic operators perform different tasks on
operands.

Example: Arithmetic Operation

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

Ministry of Education 602


Grade 11 Web Design and Development Student Module

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.

Example: Post and Pre Increment/Decrement

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.

Example: + Operator with String

let a = 5, b = "Hello ", c = "World!", d = 10;


a + b; //returns "5Hello "
b + c; //returns "Hello World!"
a + d; //returns 15
b + true; //returns "Hello true"
c - b; //returns NaN; - operator can only used with numbers
Comparison Operators

JavaScript provides comparison operators that compare two operands and return a boolean
value true or false.

Operators Description

Ministry of Education 603


Grade 11 Web Design and Development Student Module

Operators Description

== Compares the equality of two operands without considering type.

=== Compares equality of two operands with type.

!= Compares inequality of two operands.

> 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.

The following example demonstrates the comparison operators.

Example: JavaScript Comparison Operators

let a = 5, b = 10, c = "5";


let x = a;
a == c; // returns true
a === c; // returns false
a == x; // returns true
a != b; // returns true
a > b; // returns false
a < b; // returns true
a >= b; // returns false
a <= b; // returns true
Logical Operators

Ministry of Education 604


Grade 11 Web Design and Development Student Module

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.

Example: Logical Operators

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.

Ministry of Education 605


Grade 11 Web Design and Development Student Module

Assignment Description
operators

= Assigns right operand value to the left operand.

+= 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.

Example: Assignment operators

let x = 5, y = 10, z = 15;


x = y; //x would be 10
x += 1; //x would be 6
x -= 1; //x would be 4
x *= 5; //x would be 25
x /= 5; //x would be 1
x %= 2; //x would be 1
Ternary Operator

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.

Ministry of Education 606


Grade 11 Web Design and Development Student Module

Syntax:

<Condition>? <value1>: <value2>;


The ternary operator starts with conditional expression followed by the? Operator. The
second part (after? and before :) will be executed if the condition turns out to be true.
Suppose, the condition returns false, then the third part (after :) will be executed.

Example: Ternary operator

let a = 10, b = 5;

let c = a > b? a : b; // value of c would be 10


let d = a > b? b : a; // value of d would be 5
Remember:

1. JavaScript includes operators that perform some operation on single or multiple operands (data
value) and produce a result.

2. JavaScript includes various categories of operators: Arithmetic operators, Comparison


operators, Logical operators, Assignment operators, Conditional operators.

3. Ternary operator?: is a short form of if-else condition.

[Link] JavaScript Data Types


In JavaScript, you can assign different types of values (data) to a variable e.g. string, number,
boolean, etc.

Example: A Variable with Different Types of Data

let myvariable = 1; // numeric value


myvariable = 'one'; // string value
myvariable = true; // Boolean value
In the above example, different types of values are assigned to the same variable to
demonstrate the loosely typed characteristics of JavaScript. Here, 1 is the number type, 'one' is
the string type, and true is the boolean type.

Ministry of Education 607


Grade 11 Web Design and Development Student Module

JavaScript includes primitive and non-primitive data types as per the latest ECMAScript 5.1
specification.

Primitive Data Types

The primitive data types are the lowest level of the data value in JavaScript. The followings
are primitive data types in JavaScript:

Data Type Description

String String is a textual content wrapped inside ' ' or " " or ` ` (tick sign).
Example: 'Hello World!', "This is a string", etc.

Number Number is a numeric value.


Example: 100, 4521983, etc.

BigInt BigInt is a numeric value in the arbitrary precision format.


Example: 453889879865131n, 200n, etc.

Boolean Boolean is a logical data type that has only two values, true or false.

Null A null value denotes an absense of value.


Example: let str = null;

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.

Structural Data Types

The structural data types contain some kind of structure with primitive data.

Data Type Description

Object An object holds multiple values in terms of properties and methods.

Ministry of Education 608


Grade 11 Web Design and Development Student Module

Data Type Description

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");

Array An array stores multiple values using special syntax.


Example: let nums = [1, 2, 3, 4];

Learn about each data type in detail in the next section.

2.1.2 Statements, Expressions, and Comments:


Differentiate between statements (performing actions) and expressions (producing values).
Effectively structure your code using conditional statements (if/else), loops (for/while), and
functions. Leverage comments to explain your code and enhance readability.

Example

let x, y, z; // Statement 1
x = 5; // Statement 2
y = 6; // Statement 3
z = x + y; // Statement 4

JavaScript Programs

A computer program is a list of "instructions" to be "executed" by a computer.

Ministry of Education 609


Grade 11 Web Design and Development Student Module

In a programming language, these programming instructions are called statements.

A JavaScript program is a list of programming statements.

In HTML, JavaScript programs are executed by the web browser.

JavaScript Statements

JavaScript statements are composed of:

Values, Operators, Expressions, Keywords, and Comments.

This statement tells the browser to write "Hello Dolly." inside an HTML element with
id="demo":

Example

[Link]("demo").innerHTML = "Hello Dolly.";

Most JavaScript programs contain many JavaScript statements.

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;

Semicolons separate JavaScript statements.

Add a semicolon at the end of each executable statement:

Examples

let a, b, c; // Declare 3 variables


a = 5; // Assign the value 5 to a
b = 6; // Assign the value 6 to b
c = a + b; // Assign the sum of a and b to c

Ministry of Education 610


Grade 11 Web Design and Development Student Module

When separated by semicolons, multiple statements on one line are allowed:

a = 5; b = 6; c = a + b;

On the web, you might see examples without semicolons.


Ending statements with semicolon is not required, but highly recommended.

JavaScript White Space

JavaScript ignores multiple spaces. You can add white space to your script to make it more
readable.

The following lines are equivalent:

let person = "Hege";


let person="Hege";

A good practice is to put spaces around operators ( = + - * / ):

let x = y + z;

2.1.3 Type Conversions:


• Learn how to explicitly convert values between different data types using functions
like parseInt() and toString().
• Understand implicit conversions and potential pitfalls.

2.3 Control Structures and Loops


2.3.1 Conditional Statements:
Apply if, else if, and else statements to control the flow of your code based on conditions. Utilize
switch statements for complex decision-making with multiple options.

JavaScript includes if/else conditional statements to control the program flow, similar to other
programming languages.

Ministry of Education 611


Grade 11 Web Design and Development Student Module

JavaScript includes following forms of if-else statements:

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.

In the same way, you can use variables in a conditional expression.

Example: if condition

var mySal = 1000;

Ministry of Education 612


Grade 11 Web Design and Development Student Module

var yourSal = 500;


if( mySal > yourSal)
{
alert("My Salary is greater than your salary");
}

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..

Ministry of Education 613


Grade 11 Web Design and Development Student Module

}
else{
//Execute this code..
}
Example: else condition

var mySal = 500;


var yourSal = 1000;
if( mySal > yourSal)
{
alert("My Salary is greater than your salary");
}
else
{
alert("My Salary is less than or equal to your salary");
}
else if 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

var mySal = 500;


var yourSal = 1000;
if( mySal > yourSal)
{

Ministry of Education 614


Grade 11 Web Design and Development Student Module

alert("My Salary is greater than your salary");


}
else if(mySal < yourSal)
{
alert("My Salary is less than your salary");
}
JavaScript allows multiple else if statements also.

Example: Multiple if else conditions

var mySal = 500;


var yourSal = 1000;
if( mySal > yourSal)
{
alert("My Salary is greater than your salary");
}
else if(mySal < yourSal)
{
alert("My Salary is less than your salary");
}
else if(mySal == yourSal)
{
alert("My Salary is equal to your salary");
}
We will learn about switch case in the next section.

Remember:

1. Use if-else conditional statements to control the program flow.

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.

2.3.2 Looping Structures:


Iterate through sequences of data effectively using for, while, and do-while loops. Understand
nested loops and their applications.

JavaScript includes for loop like Java or C#. Use for loop to execute code repeatedly.

for (initializer; condition; iteration)


{
// Code to be executed
}
The for loop requires following three parts.

• Initializer: Initialize a counter variable to start with


• Condition: specify a condition that must evaluate to true for next iteration
• Iteration: increase or decrease counter

Example: for loop


for (var i = 0; i < 5; i++)
{
[Link](i);
}
Output:
01234
In the above example, var i = 0 is an initializer statement where we declare a variable i with
value 0. The second part, i < 5 is a condition where it checks whether i is less than 5 or not.
The third part, i++ is iteration statement where we use ++ operator to increase the value of i to
1. All these three parts are separated by semicolon;

616
Student Module

The for loop can also be used to get the values for an array.

Example: for loop


var arr = [10, 11, 12, 13, 14];
for (var i = 0; i < 5; i++)
{
[Link](arr[i]);
}
Output:
10 11 12 13 14
Please note that it is not mandatory to specify an initializer, condition and increment
expression into bracket. You can specify initializer before starting for loop. The condition and
increment statements can be included inside the block.

Example: for loop


var arr = [10, 11, 12, 13, 14];
var i = 0;
for (; ;) {
if (i >= 5)
break;
[Link](arr[i]);
i++;
}
Output:
10 11 12 13 14
Learn about while loop in the next section.

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){ ... }

3. The code block can be wrapped with { } brackets.

4. An initializer can be specified before starting for loop. The condition and increment statements
can be included inside the block.

2.3.3 Break and Continue Statements:


Control the flow of loops using break to exit and continue to skip iterations.

JavaScript Line Length and Line Breaks

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 Code Blocks

JavaScript statements can be grouped together in code blocks, inside curly brackets {...}.

The purpose of code blocks is to define statements to be executed together.

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.

2.3.4 Error Handling:


Implement try...catch blocks to gracefully handle runtime errors, preventing crashes and
improving user experience.

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 catch block does not handle syntax errors.

JavaScript provides error-handling mechanism to catch runtime errors using try-catch-finally


block, similar to other languages like Java or C#.

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
}

Ministry of Education 619


Student Module
• Try: wrap suspicious code that may throw an error in try block.

• 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.

Let's look at simple error handling examples.

Example: Error Handling in JS

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

The finally block executes regardless of whatever happens.

Example: finally Block

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

Uses throw keyword to raise a custom error.

Example: throw Error

try
{
throw "Error occurred";
}
catch(ex)
{
alert(ex);
}

Ministry of Education 621


Grade 11 Web Design and Development Student Module

You can use JavaScript object for more information about an error.

Example: throw error with error info

try
{
throw {
number: 101,
message: "Error occurred"
};
}
catch (ex) {
alert([Link] + "- " + [Link]);
}

2.4 Functions in JavaScript

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.

Ministry of Education 622


Grade 11 Web Design and Development Student Module

Our Reserved Words Reference lists all JavaScript keywords.

Keyword Description
Var Declares a variable

Let Declares a block variable

const Declares a block constant

If Marks a block of statements to be executed on a condition

switch Marks a block of statements to be executed in different cases

For Marks a block of statements to be executed in a loop

function Declares a function

return Exits a function

try Implements error handling to a block of statements

Functions make JavaScript code more readable, organized, reusable, and maintainable.

function <function-name>(arg1, arg2, arg3,...)


{
//write function code here
};
In JavaScript, a function can be defined using the function keyword, followed by the name of a
function and parentheses. Optionally, a list of input parameters can be included within the
parentheses. The code block that needs to be executed when the function is called is written
within curly braces.

2.4.1 Defining and Invoking Functions:


Write reusable blocks of code with defined functionality using the function keyword. Call
functions to execute their code and pass necessary arguments.

Ministry of Education 623


Grade 11 Web Design and Development Student Module

The following defines a function named greet that will display an alert box.

Example: Define a Function

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.

Example: Calling a 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.

Example: Function Expression

var add = function (num1, num2) {


return num1 + num2;
};
var result = add(10, 20);//returns 30
Anonymous 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

Ministry of Education 624


Grade 11 Web Design and Development Student Module

Anonymous functions are typically used in functional programming e.g. callback function,
creating closure or immediately invoked function expression.

Example: Anonymous Function

let numbers = [10, 20, 30, 40, 50];


let squareNumbers = [Link](function(number) {
return number * number;
});
Arrow Functions

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.

Example: Arrow Function

let square = num => num * num;


let result = square(5);
[Link](result); //25
Nested Functions

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.

Ministry of Education 625


Grade 11 Web Design and Development Student Module

Example: Nested 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.

Arrow functions were introduced in ES6.

Arrow functions allow us to write shorter function syntax:

let myFunction = (a, b) => a * b;

Before Arrow:

hello = function() {
return "Hello World!";
}

With Arrow Function:

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:

Ministry of Education 626


Grade 11 Web Design and Development Student Module

Arrow Functions Return Value by Default:

hello = () => "Hello World!";

Note: This works only if the function has only one statement.

If you have parameters, you pass them inside the parentheses:

Arrow Function with Parameters:

hello = (val) => "Hello " + val;

In fact, if you have only one parameter, you can skip the parentheses as well:

Arrow Function without Parentheses:

hello = val => "Hello " + val;

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.

Ministry of Education 627


Grade 11 Web Design and Development Student Module

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

With an arrow function this represents the owner of the function:

// 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.

2.4.4 Parameters, Arguments, and Default Values:


Accept input data into functions using parameters and provide default values when necessary.
Understand how arguments are passed and used within functions.

Ministry of Education 628


Grade 11 Web Design and Development Student Module

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.

Example: Function Parameters

function greet(firstName, lastName) {


alert("Hello " + firstName + " " + lastName);
}
greet("Abebe", "Jobs");
JavaScript is a dynamic type scripting language, so a function parameter can have a value of
any data type.

Example: Function Parameters

function greet(firstName, lastName) {


alert("Hello " + firstName + " " + lastName);
}
greet("Bill", "Gates");
greet(100, 200);
You can pass fewer or more arguments while calling a function. If you pass fewer arguments
then the rest of the parameters will become undefined. If you pass more arguments then
additional arguments will be ignored.

Example: Function Parameters

function greet(firstName, lastName) {


alert("Hello " + firstName + " " + lastName);
}
greet("Abebe", "Jobs", "Mr."); // display Hello Abebe Jobs
greet("Bill"); // display Hello Bill undefined
greet(); // display Hello undefined undefined
You can also use the built-in arguments object to access parameters inside a function.

Ministry of Education 629


Grade 11 Web Design and Development Student Module

Return a Value from a Function

A function can return a value to the calling code using the return keyword followed by a
variable or a value.

The following returns a number 10.

Example: Return a value of a Function

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.

Example: Return value from a Function

function Sum(num1, num2) {


return num1 + num2;
};
var result = Sum(10,20); // returns 30

Ministry of Education 630


Grade 11 Web Design and Development Student Module

A function can return another function in JavaScript.

Example: Function Returning a Function

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.

Example: String literals

"Hello World"
'Hello World'
`Hello World`
The string literal can be assigned to a variable using the equal to = operator.

Example: String Variables

let str1 = "This is a double quoted string.";


let str2 = 'This is a single quoted string.';
let str3 = `This is a template string. `;
The template string (using backticks) is used when you want to include the value of a variable
or expressions into a string. Use ${variable or expression} inside backticks as shown below.

Ministry of Education 631


Grade 11 Web Design and Development Student Module

Example: Template String

let amount = 1000, rate = 0.05, duration = 3;


let result = `Total Amount Payble: ${amount*(1 + rate*duration)}`;
The template string can be spanned in multiple lines which is not allowed with a single or
double quoted string, as shown below.

Example: Template String

let str1 = `This


is
multi-line
string`;
/*let str2 = "This
will
give
error"; */
JavaScript string can be treated like a character array. You can access a character in a string
using square brackets [index] or using the [Link](pos) method.

Example: String as array

let str = 'Hello World';


let ch1 = str[0] // H
let ch2 = str[1] // e
let ch3 = [Link](2) // l
let ch4 = [Link](3) // l
str[4] = "P"; //error

Ministry of Education 632


Grade 11 Web Design and Development Student Module

JavaScript strings can be accessed using a for loop, as shown below.

Example: Use for Loops

let str = 'Hello World';


for(let i =0; i< [Link]; i++)
[Link](str[i]);
for(let ch of str)
[Link](ch);
Quotes inside String

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.

Example: Quotes in string

let str1 = "This is 'simple' string";


let str2 = 'This is "simple" string';
let str3 = `This is 'simple' and "easy" string`;
If you want to include the same quotes in a string value as surrounding quotes then use a
backward slash (\) before the quotation mark inside the string value.

Example: Quotes in string

let str1 = "This is \"simple\" string";


let str2 = 'This is \'simple\' string';

Ministry of Education 633


Grade 11 Web Design and Development Student Module

String Concatenation

JavaScript string can be concatenated using the + operator or [Link]() method.

Example: String concatenation

let str1 = 'Hello ';


let str2 = "World ";
let str3 = str1 + str2; //Hello World
let str4 = [Link](str2);//Hello World
String Objects

JavaScript allows you to create a string object using the new keyword, as shown below.

Example: String object

let str1 = new String(); //create string object


str1 = 'Hello World'; //assign value
// or
let str2 = new String('Hello World'); //create and assign value
String objects and string literals are different. The typeof() method will return the type of a
variable. The following distinguished string and string objects.

Example: String object

let str1 = new String('Hello World');


let str2 = "Hello World";
typeof(str1); //"object"
typeof(str2); //"string"
Strings Comparison

Two strings can be compared using <, >, ==, === operator,
and [Link](string) method.

Ministry of Education 634


Grade 11 Web Design and Development Student Module

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.

Example: String Comparison

[Link]("a" < "b"); //true


[Link]("b" < "a"); //false
[Link]("Apple" == "Apple"); //true
[Link]("Apple" == "apple"); //false
[Link]("Apple" === "Apple"); //true
[Link]("Apple" === "apple"); //false
[Link]("Apple".localeCompare("Apple")); //0
[Link]("Apple".localeCompare("apple")); //1
Note that the === operator compares the reference of strings objects and not the values.

Example: String Object Comparison

let str1 = "Hello";


let str2 = 'Hello';
let str3 = new String('Hello');
[Link](str1 == str2); //true
[Link](str1 === str2);//true
[Link](str1 == str3); //true
[Link](str1 === str3);//false

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.

Ministry of Education 635


Grade 11 Web Design and Development Student Module

2.5 DOM Manipulation and Event Handling


DOM manipulation and event handling are crucial aspects of JavaScript development. The
Document Object Model (DOM) represents the structure of a web page, and through DOM
manipulation, we can dynamically modify its content, style, and structure. JavaScript provides
powerful functions and methods to access, create, and modify DOM elements. Event handling
allows us to respond to user interactions such as clicks, mouse movements, and keystrokes. By
attaching event listeners to specific elements, we can execute JavaScript code when these events
occur. This combination of DOM manipulation and event handling empowers developers to
create interactive and dynamic web applications.

2.6 Document Object Model (DOM):


Grasp the tree-like structure of HTML documents represented by the DOM. Navigate and access
specific elements in the DOM using their IDs, classes, or names.

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.

The following declares an array with five numeric values.

let numArr = [10, 20, 30, 40, 50];


In the above array, numArr is the name of an array variable. Multiple values are assigned to it
by separating them using a comma inside square brackets as [10, 20, 30, 40, 50]. Thus,
the numArr variable stores five numeric values. The numArr array is created using the literal
syntax and it is the preferred way of creating arrays.

Another way of creating arrays is using the Array() constructor, as shown below.

let numArr = new Array(10, 20, 30, 40, 50);


Every value is associated with a numeric index starting with 0. The following figure illustrates
how an array stores values.

Ministry of Education 636


Grade 11 Web Design and Development Student Module

JavaScript Array Representation

The following are some more examples of arrays that store different types of data.

Example: Array Literal Syntax


let stringArray = ["one", "two", "three"];
let numericArray = [1, 2, 3, 4];
let decimalArray = [1.1, 1.2, 1.3];
let booleanArray = [true, false, false, true];
It is not required to store the same type of values in an array. It can store values of different
types as well.

let data = [1, "Abebe", "DC", true, 255000, 5.5];


Get Size of an Array

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.

Example: Get Array Size

let cities = ["Addis_Ababa", "New York", "Paris", "Sydney"];


[Link]([Link]); //4
cities[4] = "Delhi";
[Link]([Link]); //5
Accessing and Modifying DOM Elements:
Change element content, styles, attributes, and more using JavaScript [Link]
dynamic and interactive web pages by manipulating the DOM.

You can update the elements of an array at a particular index using arrayName[index] =
new_value syntax.

Ministry of Education 637


Grade 11 Web Design and Development Student Module

Example: Update Array Elements

let cities = ["Addis_Ababa", "New York", "Paris", "Sydney"];


cities[0] = "Delhi";
cities[1] = "Los angeles";
[Link](cities); //["Delhi", "Los angeles", "Paris", "Sydney"]
Array elements (values) can be accessed using an index. Specify an index in square brackets
with the array name to access the element at a particular index like arrayName[index]. Note
that the index of an array starts from zero.

Example: Accessing Array Elements

let numArr = [10, 20, 30, 40, 50];


[Link](numArr[0]); // 10
[Link](numArr[1]); // 20
[Link](numArr[2]); // 30
[Link](numArr[3]); // 40
[Link](numArr[4]); // 50
let cities = ["Addis_Ababa", "New York", "Paris", "Sydney"];
[Link](cities[0]); // "Addis_Ababa"
[Link](cities[1]); // "New York"
[Link](cities[2]); // "Paris"
[Link](cities[3]); // "Sydney"
//accessing element from nonexistance index
[Link](cities[4]); // undefined
For the new browsers, you can use the [Link](pos) method to get the element from the specified
index. This is the same as arr[index] except that the at() returns an element from the last element
if the specified index is negative.

Ministry of Education 638


Grade 11 Web Design and Development Student Module

Example: Accessing Array using at()

let numArr = [10, 20, 30, 40, 50];


[Link]([Link](0)); // 10
[Link]([Link](1)); // 20
[Link]([Link](2)); // 30
[Link]([Link](3)); // 40
[Link]([Link](4)); // 50
[Link]([Link](5)); // undefined
//passing negative index
[Link]([Link](-1)); // 50
[Link]([Link](-2)); // 40
[Link]([Link](-3)); // 30
[Link]([Link](-4)); // 20
[Link]([Link](-5)); // 10
[Link]([Link](-6)); // undefined
You can iterate an array using [Link]() , for, for-of, and for-in loop, as shown below.

Example: Accessing Array Elements

let numArr = [10, 20, 30, 40, 50];


[Link](i => [Link](i)); //prints all elements
for(let i=0; i<[Link]; i++)
[Link](numArr[i]);
for(let i of numArr)
[Link](i);
for(let i in numArr)
[Link](numArr[i]);

Ministry of Education 639


Grade 11 Web Design and Development Student Module

Adding and Removing Elements Dynamically:


Programmatically add or remove elements from the DOM based on user actions or other
conditions. Build complex and interactive user interfaces.

Adding New Elements

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.

Example: Add Array Elements

let cities = ["Addis_Ababa", "New York", "Paris", "Sydney"];


cities[4] = "Delhi"; //add new element at last
[Link](cities); //["Addis_Ababa", "New York", "Paris", "Sydney", "Delhi"]
cities[[Link]] = "London";//use length property to specify last index
[Link](cities); //["Addis_Ababa", "New York", "Paris", "Sydney", "Delhi", "London"]
cities[9] = "Pune";
[Link](cities); //["Addis_Ababa", "New York", "Paris", "Sydney", "Delhi", "Londen",
undefined, undefined, undefined, "Pune"]
In the above example, cities [9] = "Pune" adds "Pune" at 9th index and all other non-declared
indexes as undefined.

The recommended way of adding elements at the end is using the push() method. It adds an
element at the end of an array.

Example: Add Element At Last using push()

let cities = ["Addis_Ababa", "New York", "Paris", "Sydney"];


[Link]("Delhi"); //add new element at last
[Link](cities); //["Addis_Ababa", "New York", "Paris", "Sydney", "Delhi"]

Ministry of Education 640


Grade 11 Web Design and Development Student Module

Use the unshift() method to add an element to the beginning of an array.

Example: Add Element using unshift()

let cities = ["Addis_Ababa", "New York", "Paris", "Sydney"];


[Link]("Delhi"); //adds new element at the beginning
[Link](cities); //["Delhi", "Addis_Ababa", "New York", "Paris", "Sydney"]
[Link]("London", "Pune"); //adds new element at the beginning
[Link](cities); //["London", "Pune", "Delhi", "Addis_Ababa", "New York", "Paris",
"Sydney"]
Remove Array Elements

The pop() method returns the last element and removes it from the array.

Example: Remove Last Element

let cities = ["Addis_Ababa", "New York", "Paris", "Sydney"];


let removedCity = [Link](); //returns and removes the last element
[Link](cities); //["Addis_Ababa", "New York", "Paris"]
The shift() method returns the first element and removes it from the array.

Example: Remove First Element

let cities = ["Addis_Ababa", "New York", "Paris", "Sydney"];


let removedCity = [Link](); //returns first element and removes it from array
[Link](cities); //["New York", "Paris", "Sydney"]

Ministry of Education 641


Grade 11 Web Design and Development Student Module

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.

Example: Remove Middle Elements

let cities = ["Addis_Ababa", "New York", "Paris", "Sydney"];


let cityToBeRemoved = "Paris";
let mycities = [Link](function(item) {
return item !== cityToBeRemoved
})
[Link](mycities); //["Addis_Ababa", "New York", "Sydney"]
[Link](cities); //["Addis_Ababa", "New York", "Paris", "Sydney"]
Event Handling and Propagation:
Respond to user interactions (clicks, key presses, etc.) by attaching event listeners to DOM
elements. Understand event bubbling and capturing for advanced event handling. A JavaScript
can be executed when an event occurs, like when a user clicks on an HTML element. To execute
code when a user clicks on an element, add JavaScript code to an HTML event attribute:

>

Examples of HTML events:

• When a user clicks the mouse


• When a web page has loaded
• When an image has been loaded
• When the mouse moves over an element
• When an input field is changed
• When an HTML form is submitted
• When a user strokes a key

Ministry of Education 642


Grade 11 Web Design and Development Student Module

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>

In this example, a function is called from the event handler:

Example

<!DOCTYPE html>
<html>
<body>
<h1 on this text!</h1>
<script>
function changeText(id) {
[Link] = "Ooops!";
}
</script>
</body>
</html>

Ministry of Education 643


Grade 11 Web Design and Development Student Module

HTML Event Attributes

To assign events to HTML elements you can use event attributes.

Example

Assign an onclick event to a button element:

<button it</button>

In the example above, a function named displayDate will be executed when the button is clicked.

Assign Events Using the HTML DOM

The HTML DOM allows you to assign events to HTML elements using JavaScript:

Example

Assign an onclick event to a button element:

<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

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.

Ministry of Education 644


Grade 11 Web Design and Development Student Module

The onload and onunload events can be used to deal with cookies.

Example

<body >

The oninput Event

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

<input type="text" id="fname" >

The onchange Event

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:

1. What are the basic data types in JavaScript?


2. How do you declare and initialize a variable in JavaScript?
3. What are JavaScript operators? Provide examples of arithmetic, comparison, and logical
operators.
4. How do you use if, else if, and else statements in JavaScript?
5. What is a function in JavaScript?
6. How do you declare a function in JavaScript? Provide examples of both function declarations
and function expressions.
7. Explain the concept of parameters and arguments in JavaScript functions.

Ministry of Education 645


Grade 11 Web Design and Development Student Module

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.

Unit Review Questions

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?

Ministry of Education 646


Grade 11 Web Design and Development Student Module

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

2. What is the purpose of control structures and loops in JavaScript?


a) Manipulating the Document Object Model (DOM)
b) Adding interactivity to web pages
c) Handling errors and exceptions
d) Defining and invoking functions
3. What are conditional statements used for in JavaScript?
a) Modifying the Document Object Model (DOM)
b) Controlling the flow of program execution based on conditions
c) Accessing and modifying DOM elements
d) Defining and invoking functions
4. What is the purpose of error handling in JavaScript?
a) Modifying the Document Object Model (DOM)
b) Adding interactivity to web pages
c) Handling errors and exceptions in code execution
d) Accessing and modifying DOM elements

Ministry of Education 647


Grade 11 Web Design and Development Student Module

5. What is the purpose of functions in JavaScript?


a) Defining and invoking functions
b) Accessing and modifying DOM elements
c) Controlling the flow of program execution
d) Handling errors and exceptions
6. What is the Document Object Model (DOM) in JavaScript?
a) A programming language used for server-side development
b) A model that represents the structure of an HTML document
c) A library for accessing and modifying databases
d) A tool for debugging JavaScript code
7. How can you access and modify DOM elements in JavaScript?
a) By using CSS selectors
b) By using JavaScript methods and properties
c) By using jQuery library functions
d) By using HTML tags directly

Ministry of Education 648


Grade 11 Web Design and Development Student Module

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]

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 Validation
✓ Apply Form validation

Key Terms: Validation, Form Validation and web form.

3.1. Validating User Input


Dear learners! "What is form validation and why is it important in web applications?"
Form validation is a crucial aspect of user input validation in web applications. It ensures that the
data entered by users in a form meets the required criteria and is valid before it is processed or
stored. By validating user input, you can prevent errors, improve data quality, enhance security,
and provide a better user experience.

Here are some details about form validation for trainees:

3.1.1 Introduction to Validation:

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.

Ministry of Education 649


Grade 11 Web Design and Development Student Module

• Validation can be performed on various types of user input, such as text fields,
checkboxes, radio buttons, dropdowns, and file uploads.

3.1.2 Form Validation:


Form validation in JavaScript is a technique used to ensure that user input in web forms meets
certain criteria or requirements before it is submitted to the server. It helps validate the data
entered by the user and prevents the submission of incorrect or incomplete form data.
Here's an example 1:- of how you can perform form validation in JavaScript:
HTML:
html
<form id="myForm" > <label for="name">Name:</label>
<input type="text" id="name" required>
<label for="email">Email:</label>
<input type="email" id="email" required>
<input type="submit" value="Submit">
</form>
JavaScript: javascript
function validateForm(event) {
[Link](); // Prevent form submission
// Get form inputs
var nameInput = [Link]("name");
var emailInput = [Link]("email");
// Validate name
if ([Link] === "") {
alert("Please enter your name.");
return false; // Stop form submission
}
// Validate email
if ([Link] === "") {
alert("Please enter your email.");

Ministry of Education 650


Grade 11 Web Design and Development Student Module

return false; // Stop form submission


}
// Additional validation logic for email format, password requirements, etc.
// Form is valid, submit it
[Link]("myForm").submit();
}
In this example, the validateForm function is called when the form is submitted. It first prevents
the default form submission using [Link](). Then, it retrieves the input values
from the form fields and performs the desired validation checks.
If any validation condition fails, an alert is shown with an appropriate error message, and return
false stops the form submission. If all validation conditions pass, the form is submitted
using [Link]("myForm").submit().
Example 2: Form validation in JavaScript using HTML5 involves implementing validation
rules on form fields to ensure that user input meets specific criteria before it is submitted. Here's
an example of how you can perform form validation using HTML5 attributes and JavaScript:
1. HTML Form Structure:
html
<form id="myForm" action="[Link]" method="POST">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>

<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>

<input type="submit" value="Submit">


</form>

Ministry of Education 651


Grade 11 Web Design and Development Student Module

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

var form = [Link]("myForm");

[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.

Ministry of Education 652


Grade 11 Web Design and Development Student Module

Example 3: Here's an additional example of form validation in JavaScript using HTML5:


HTML Form Structure:
html
<form id="myForm" action="[Link]" method="POST">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required minlength="4" maxlength="10"
>

<label for="password">Password:</label>
<input type="password" id="password" name="password" required minlength="6">

<label for="confirmPassword">Confirm Password:</label>


<input type="password" id="confirmPassword" name="confirmPassword" required>

<input type="submit" value="Submit">


</form>
In this example, we have a form with three fields: username, password, and confirmPassword.
The "required" attribute is added to ensure that these fields are mandatory. Additionally, we use
the "minlength" and "maxlength" attributes to specify the minimum and maximum length for the
username field and the minimum length for the password field.
JavaScript Validation:
javascript
var form = [Link]("myForm");
var password = [Link]("password");
var confirmPassword = [Link]("confirmPassword");
[Link]("submit", function(event) {
if (![Link]()) {
[Link](); // Prevent form submission if validation fails
} else if ([Link] !== [Link]) {

Ministry of Education 653


Grade 11 Web Design and Development Student Module

[Link](); // Prevent form submission if password and confirm password do not


match
alert("Passwords do not match!");
}
});
In this JavaScript code, we get references to the form element, the password field, and the
confirmPassword field using their respective IDs. We add an event listener for the form's
"submit" event. Inside the event handler function, we first check if the form is valid using
the checkValidity() method. If the form is not valid, we use [Link]() to prevent the
form submission.
Additionally, we check if the entered passwords match by comparing the values of the password
and confirm Password fields. If they don't match, we prevent the form submission and display an
alert message to the user.
This example demonstrates how to implement custom validation logic using JavaScript in
addition to HTML5's built-in form validation. By combining both approaches, you can create
robust form validation to ensure that user input meets specific criteria before submitting the
form.
You can add more validation logic based on your specific requirements, such as checking for the
correct email format, password strength, or validating specific fields.
Trainees can practice implementing form validation using HTML, CSS, JavaScript, and server-
side languages/frameworks like PHP, Python (Django/Flask), Ruby (Ruby on Rails), or .NET
([Link]) depending on their learning objectives and the technologies used in their training
environment. They can start with simple form validation scenarios and gradually progress to
more complex validation requirements based on real-world examples. It's also beneficial to
explore existing libraries and frameworks that provide validation utilities to streamline the
development process.

Ministry of Education 654


Grade 11 Web Design and Development Student Module

Self-check 3-1:

1. What is the purpose of form validation in web applications?


2. What are the two main types of validation in form validation?

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.

Unit Review Questions

1. What is the purpose of validation?

a) To secure user input


b) To ensure accurate data entry
c) To prevent submission of incorrect or incomplete data
d) All of the above

Ministry of Education 655


Grade 11 Web Design and Development Student Module

2. What is form validation?


a) Verifying the authenticity of a web form
b) Checking the data entered by the user against predefined rules
c) Encrypting form data before submission
d) Converting form data into JSON format
3. Which of the following is true about validation?
a) It can be performed on the client-side using JavaScript
b) It can be performed on the server-side using a backend language
c) Both a) and b)
d) None of the above
4. How can form validation be implemented in JavaScript?
a) By using if-else statements to check input values
b) By defining rules for each form field and validating them
c) By using regular expressions to match patterns in input
d) All of the above
5. What are some common validation checks that can be performed on user input?
a) Checking for required fields c) Verifying password strength
b) Validating email addresses d) All of the above
6. What is the purpose of preventing form submission in validation?
a) To display error messages to the c) To redirect the user to another
user page
b) To clear the form fields d) None of the above

Ministry of Education 656


Grade 11 Web Design and Development Student Module

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

Ministry of Education 657


Grade 11 Web Design and Development Student Module

Answers for Self-Check Questions

Answers for Self-check 1-1

1. Distinguishing JavaScript from other programming languages:

• 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;

// Using let (preferred for block-scoped variables)


let name = 'Alice';

// Using const (for constants)


const PI = 3.14;

3. Including JavaScript in HTML files:

• 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:

Ministry of Education 658


Grade 11 Web Design and Development Student Module

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.

Answers for Self-check 2-1

1. Basic data types in JavaScript:


o JavaScript has primitive data types such as number, string, boolean, null,
undefined, as well as object and symbol.
2. Declaring and initializing a variable in JavaScript:
o Using var, let, or const followed by the variable name and optionally initializing it
with a value.

javascript
Copy code
// Using var
var age = 30;

// Using let (block-scoped)

Ministry of Education 659


Grade 11 Web Design and Development Student Module

let name = 'John';

// Using const (immutable)


const PI = 3.14;

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

4. Using if, else if, and else statements:


o Conditional statements are used to execute different blocks of code based on
different conditions.

javascript
Copy code
let num = 10;

if (num > 0) {
[Link]('Number is positive');

Ministry of Education 660


Grade 11 Web Design and Development Student Module

} else if (num < 0) {


[Link]('Number is negative');
} else {
[Link]('Number is zero');
}

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

7. Parameters and arguments in JavaScript functions:


o Parameters are variables listed as part of the function definition.
o Arguments are the values passed to the function when it is invoked.

javascript
Copy code
function add(a, b) { // a and b are parameters
return a + b;
}

let result = add(3, 5); // 3 and 5 are arguments


[Link](result); // 8

Ministry of Education 661


Grade 11 Web Design and Development Student Module

Answers for Self-check 3-1

1. Purpose of form validation in web applications:

• 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.

2. Two main types of validation in form validation:

• 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.

Ministry of Education 662

You might also like