0% found this document useful (0 votes)
3 views174 pages

Module 6

This document is a comprehensive guide on JavaScript, covering its definition, characteristics, syntax, and applications in web development. It includes detailed sections on scripting languages, interactivity using JavaScript, validating user input, and setting up a development environment. Additionally, it discusses JavaScript features, advantages, limitations, and variable handling, aimed at Grade 11 students studying web design and development.

Uploaded by

onep44128
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)
3 views174 pages

Module 6

This document is a comprehensive guide on JavaScript, covering its definition, characteristics, syntax, and applications in web development. It includes detailed sections on scripting languages, interactivity using JavaScript, validating user input, and setting up a development environment. Additionally, it discusses JavaScript features, advantages, limitations, and variable handling, aimed at Grade 11 students studying web design and development.

Uploaded by

onep44128
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

Grade-11 Web Design and Development 1


UNIT 1: SCRIPTING LANGUAGE
1.1 Identify scripting language
1.2 Introduction to JavaScript (JS)

UNIT 2: Apply INTERACTIVITY USING JAVASCRIPT

2.1 Overview of interactivity using JavaScript


2.2 JavaScript Syntax and Basic Concepts
2.3 Control Structures and Loops
2.4 Functions in JavaScript
2.5 DOM Manipulation and Event Handling
2.6 Document Object Model (DOM)

UNIT 3: VALIDATING USER INPUT

3.1 Introduction to Validation

Grade-11 Web Design and Development 2


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)

Grade-11 Web Design and Development 3


1.1 Identify scripting language
1. Introduction to Scripting Languages
What is a Scripting Language?
A scripting language is a type of programming
language used to automate tasks that would
otherwise be done manually.
o These languages are interpreted, not compiled.

Grade-11 Web Design and Development 4


Characteristics of Scripting Languages:
[Link] Execution: Runs directly without a compiler

(e.g., JavaScript engine in browsers).

[Link]-Level Syntax: Easy to read/write for beginners.

[Link] Typing: No need to define data types; types can change at runtime.

3. Built-in libraries and frameworks: Easier to perform common tasks and


interact with various resources or APIs

[Link] Development: Ideal for fast prototyping and development.

[Link] & Versatile: Great for writing small programs to automate tasks.

Grade-11 Web Design and Development 5


Examples:

oClient-Side: JavaScript

oServer-Side: PHP, Python, Ruby


JavaScript(programming with [Link])

oShell Scripting: Bash, Power Shell

Grade-11 Web Design and Development 6


2. JavaScript: Preface & History

What is JavaScript?

oHigh-level, interpreted scripting language

oCreated by Brendan Eich in 1995

oOriginally called Live Script

oDesigned to add interactivity to websites

Where is JavaScript used?

oFrontend (Browser)

oBackend ([Link])

oMobile apps (React Native)

oDesktop apps (Electron)

oGame development ([Link])


Grade-11 Web Design and Development 7
3. Role of JavaScript in Web Development
JavaScript Enhances:

oInteractivity: Adds dynamic behavior (like sliders, animations)

oUser Input Handling: Validates forms before submitting

oDOM Manipulation: Dynamically change HTML/CSS

oAPIs: Communicate with external services using AJAX/Fetch

oSingle Page Applications (SPAs): Load content dynamically without full


page refresh

Grade-11 Web Design and Development 8


1.2.3. Features of JavaScript
Feature Description
Object-Centered Uses objects like window, document
Client-side Runs in the browser, doesn't need a server
Validation Checks form fields before submission
Conditional Statements Uses if, else, switch
Loops Executes repetitive tasks (for, while)
Built-in Functions Examples: parseInt(), isNaN()

Event Handling Reacts to mouse clicks, key presses

Dynamic Typing Type of variable can change at runtime

Lightweight No need to install compiler or packages

Case Sensitive Variable ≠ variable


Grade-11 Web Design and Development 9
5. Application Areas of JavaScript
Client-Side Applications:
o Form Validation
o DOM Manipulation
o Dynamic user interface updates
o Pop-up alerts and notifications
Server-Side with [Link]:
o File handling
o Database access
o Backend APIs
Grade-11 Web Design and Development 10
Other Uses:

oPresentations (RevealJS, BespokeJS)

oGames (using Phaser or [Link])

oDesktop apps (Electron)

Grade-11 Web Design and Development 11


6. Advantages of JavaScript

Reduces server load (via client-side validation)

Improves user experience (instant feedback)

Platform independent (runs in all modern browsers)

Large ecosystem (many libraries and frameworks)

High job demand in the market

Grade-11 Web Design and Development 12


7. Limitations of JavaScript

Cannot read/write local files (security reasons)

No multithreading (executes line-by-line)

Browser dependent (some features behave


differently across browsers)

Grade-11 Web Design and Development 13


8. Setting Up JavaScript Development Environment
Tools Required:
o Editor: VS Code, Atom, Notepad++
o Browser: Chrome, Firefox, Edge
o Optional IDEs: WebStorm, Eclipse
Steps:
1. Install editor and browser
2. Create project folder
3. Write HTML file with <script> tag
4. Write JavaScript code inline or externally
5. Open HTML file in browser and test
Grade-11 Web Design and Development 14
o 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]

Grade-11 Web Design and Development 15


Global Attributes
Attribute Usage

<script async> executes the script asynchronously along with the rest of the
async page.

<script crossorigin="anonymous|use-credentials"> allows error logging for sites


crossorign which use a separate domain for static media. Value anonymous do not send
credentials, whereas use-credentials sends the credentials.

<script defer> executes the script after the document is parsed and before
defer firing DOMContentLoaded event.

<script src="uri\path to resource"> specifies the URI/path of an external script


src file;

<script type="text\javascript"> specifies the type of the containing script e.g.


type text\javascript, text\html, text\plain, application\json, application\pdf, etc.

<script referrerpolicy="no-referrer"> specifies which referrer information to


referrerpolicy send when fetching a script. Values can be no-referrer, no-referrer-when
downgrade, origin, same-origin, strict-origin, etc.

<script integrity="sha384-oqVuAfXRKap7fdgc"> specifies that a user agent can


integrity use to verify that a fetched resource has been delivered free of unexpected
manipulation.

<script nomodule> specifies that the script should not be executed in browsers
nomodule supporting ES2015 modules.
Grade-11 Web Design and Development 16
Grade-11 Web Design and Development 17
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

Grade-11 Web Design and Development 18


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

Grade-11 Web Design and Development 19


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.
some important characteristics of JavaScript syntax in this
section.
.

Grade-11 Web Design and Development 20


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


Grade-11 Web Design and Development 21
Variables
In JavaScript, a variable is declared with or without the var keyword.

Example: JavaScript Statements


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

Grade-11 Web Design and Development 22


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 one = 1; two = 2; three = 3; //three different statements
var four = 4; //single statement
var five = "Five" //single statement without ;
</script>

Grade-11 Web Design and Development 23


Whitespaces
JavaScript ignores multiple spaces and tabs.
The following statements are the same.
Example:
<script>Whitespaces in JavaScript
var one =1;
var one = 1;
var one = 1;
</script>

Grade-11 Web Design and Development 24


Code Comments
A comment is single or multiple lines, which give some information about
the current program. Comments are not for execution.
Write comment after double slashes // or write multiple lines of comments
between /* and */
<script>
var one =1; // this is a single line comment
/* this
is multi line
comment*/
var two = 2;
var three = 3;
</script>

Example: Comment JavaScript Code


Grade-11 Web Design and Development 25
String
A string is a text in JavaScript. The text content must be
enclosed in double or single quotation marks.
<script>
var msg = "Hello World" //JavaScript string in double quotes
var msg = 'Hello World' //JavaScript string in single quotes
</script>

Example: String in JavaScript

Grade-11 Web Design and Development 26


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>

Grade-11 Web Design and Development 27


Boolean
As in other languages, JavaScript also includes true
and false as a Boolean value.
<script>
var yes = true;
var no = false;
</script>

Example: Booleans in JavaScript

Grade-11 Web Design and Development 28


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
Grade-11 Web Design and Development 29
2.2.1 Variables, Data Types, and Operators:
To declare and use variables of different data types
onumbers,
ostrings,
oBooleans,
oobjects,
oarrays.

Grade-11 Web Design and Development 30


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


Grade-11 Web Design and Development 31
Example: Variable Declaration
let msg; // declaring a variable without assigning a value

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

let msg;
msg = "Hello JavaScript!"; // assigning a string value

Example: Variable Initialization

Grade-11 Web Design and Development 32


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

Grade-11 Web Design and Development 33


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

var num = 100;


var num = 200; //Ok
Grade-11 Web Design and Development 34
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

Grade-11 Web Design and Development 35


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

Example: Loosely Typed Variable

Grade-11 Web Design and Development 36


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

Example: Constant Variables


const num = 100;
num = 200; //error
Grade-11 Web Design and Development 37
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.

Grade-11 Web Design and Development 38


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.

Grade-11 Web Design and Development 39


Example: Global and Local Variable
let greet = "Hello " // global variable
function myfunction(){
let msg = "JavaScript!";
alert(greet + msg); //can access global and local variable
}
myfunction();
alert(greet);//can access global variable
alert(msg); //error: can't access local variable

Grade-11 Web Design and Development 40


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.

It is recommended to declare variable using the let keyword.

Grade-11 Web Design and Development 41


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

[Link] can be defined using let keyword. Variables defined without let or var keyword
become global variables.

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

[Link] 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.
Grade-11 Web Design and Development 42
[Link] Comments
Single Line Comments
o Single line comments start with //.
o Any text between // and the end of the line will be ignored by
JavaScript (will not be executed).
Example
// Change heading:
[Link]("myH").innerHTML = "My First Page";
// Change paragraph:
[Link]("myP").innerHTML = "My first
paragraph.";
o This example uses a single line comment at the end of each line to
explain the code:
Grade-11 Web Design and Development 43
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.

Grade-11 Web Design and Development 44


This example uses a multi-line comment (a comment block) to explain the
code:
Example
/*
The code below will change
the heading with id = "myH"
and the paragraph with id = "myP"
in my web page:
*/
[Link]("myH").innerHTML = "My First Page";
[Link]("myP").innerHTML = "My first paragraph."

Grade-11 Web Design and Development 45


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.";
*/
Grade-11 Web Design and Development 46
[Link] JavaScript Operators
An operator performs some operation on single or multiple operands

(data value) and produces a result.

For example,

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.

Grade-11 Web Design and Development 47


JavaScript includes following categories of operators.

[Link] Operators

2. Comparison Operators

[Link] Operators

[Link] Operators

5. Conditional Operators

6. Ternary Operator

Grade-11 Web Design and Development 48


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.


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

Grade-11 Web Design and Development 50


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.

Grade-11 Web Design and Development 51


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

Grade-11 Web Design and Development 52


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

Grade-11 Web Design and Development 53


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

Grade-11 Web Design and Development 54


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

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.
Grade-11 Web Design and Development 55
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

Grade-11 Web Design and Development 56


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.

Grade-11 Web Design and Development 57


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

Grade-11 Web Design and Development 58


Assignment Operators
JavaScript provides the assignment operators to assign values to variables with
less key strokes.

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

Grade-11 Web Design and Development 60


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

Grade-11 Web Design and Development 61


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

Grade-11 Web Design and Development 62


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

Grade-11 Web Design and Development 63


JavaScript includes

o primitive and

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

Grade-11 Web Design and Development 64


Data Type Description

String is a textual content wrapped inside ' ' or " " or ` ` (tick sign).
String
Example: 'Hello World!', "This is a string", etc.
Number is a numeric value.
Number
Example: 100, 4521983, etc.
BigInt is a numeric value in the arbitrary precision format.
BigInt
Example: 453889879865131n, 200n, etc.

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

A null value denotes an absense of value.


Null
Example: let str = null;

undefined is the default value of a variable that has not been assigned any
value.
Undefined 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.

Grade-11 Web Design and Development 65


Structural Data Types
The structural data types contain some kind of structure with
primitive data.
Data Type Description

An object holds multiple values in terms of properties and


methods
Example:
Object let person = {
firstName: "Aster",
lastName: "Aweke",
age: 15
};

The Date object represents date & time including days,


Date months, years, hours, minutes, seconds, and milliseconds.
Example: let today = new Date("25 July 2021");

An array stores multiple values using special syntax.


Array
Example: let nums = [1, 2, 3, 4];
Grade-11 Web Design and Development 66
2.1.2 Statements, Expressions, and Comments:
Effectively structure your code using

conditional statements (if/else),

loops (for/while), and

functions.

Grade-11 Web Design and Development 67


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

Grade-11 Web Design and Development 68


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.

Grade-11 Web Design and Development 69


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

Grade-11 Web Design and Development 70


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;

Grade-11 Web Design and Development 71


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.

Grade-11 Web Design and Development 72


2.3 Control Structures and Loops
2.3.1 Conditional Statements:
JavaScript includes following forms of if-else statements:
1. if Statement
2. if else Statement
3. else if Statement

Grade-11 Web Design and Development 73


1) 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");
Grade-11
} Web Design and Development 74
In the above example, the first if statement contains 1 > 0 as
conditional expression.

The conditional expression 1 > 0 will be evaluated to true,

The alert message "1 is greater than 0“ will be displayed,

conditional expression in second if statement will be


evaluated to false,

so "1 is less than 0" alert message will not be displayed.

Grade-11 Web Design and Development 75


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

Grade-11 Web Design and Development 76


2) else condition

Use else statement when you want to execute the code every time when if
condition evaluates to false.

The else statement must follow if or else if statement. Multiple else block
is NOT allowed.
if(condition expression)
{
//Execute this code..
}
else{
//Execute this code..
}

Grade-11 Web Design and Development 77


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

Grade-11 Web Design and Development 78


3) 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
}

Grade-11 Web Design and Development 79


Example: else if condition
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");
}

Grade-11 Web Design and Development 80


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

Grade-11 Web Design and Development 81


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.

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.

Grade-11 Web Design and Development 82


2.3.2 Looping Structures:

Iterate through sequences of data effectively using

➢ for,

➢while, and

➢do-while loops.

JavaScript includes for loop like Java or C#.

Use for loop to execute code repeatedly.

Grade-11 Web Design and Development 83


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

Grade-11 Web Design and Development 84


Example: for loop
for (var i = 0; i < 5; i++)
{
[Link](i);
}
Output:
01234

Grade-11 Web Design and Development 85


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;

Grade-11 Web Design and Development 86


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

Grade-11 Web Design and Development 87


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

Grade-11 Web Design and Development 88


Remember:

1. JavaScript for loop is used to execute code repeatedly.

2. for loop includes three parts: initialization, condition and


iteration.

e.g. for(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.

Grade-11 Web Design and Development 89


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

Grade-11 Web Design and Development 90


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:

Grade-11 Web Design and Development 91


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.

Grade-11 Web Design and Development 92


2.3.4 Error Handling:
Error handling in JavaScript involves managing and
responding to runtime errors or unexpected events that
occur during code execution.

This ensures the application remains stable and provides a


better user experience. The primary mechanism for error
handling in JavaScript is the try...catch...finally statement:

Grade-11 Web Design and Development 93


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
}

Grade-11 Web Design and Development 94


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.
Grade-11 Web Design and Development 95
Example: Error Handling in JS
try
{
var result = Sum(10, 20); // Sum is not defined yet
}
catch(ex)
{
[Link]("errorMessage").innerHTML = ex;
}

Grade-11 Web Design and Development 96


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.

Grade-11 Web Design and Development 97


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

Grade-11 Web Design and Development 98


• Throw
Uses throw keyword to raise a custom error.
Example: throw Error
try
{
throw "Error occurred";
}
catch(ex)
{
alert(ex);
}

Grade-11 Web Design and Development 99


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

Grade-11 Web Design and Development 100


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.

Grade-11 Web Design and Development 101


JavaScript Keywords
JavaScript statements often start with a keyword to
identify the JavaScript action to be performed .

Our Reserved Words Reference lists all JavaScript


keywords.

Grade-11 Web Design and Development 102


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


Grade-11 Web Design and Development 103
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.
Grade-11 Web Design and Development 104
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.
The following defines a function named greet that will display an alert
box.
Example: Define a Function
function greet() {
alert("Hello World!");
}

Grade-11 Web Design and Development 105


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

Grade-11 Web Design and Development 106


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

Grade-11 Web Design and Development 107


Example: Function Expression
var add = function (num1, num2) {
return num1 + num2;
};
var result = add(10, 20);//returns 30

Grade-11 Web Design and Development 108


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 Anonymous functions are typically used in
functional programming e.g. callback function, creating
closure or immediately invoked function expression.

Grade-11 Web Design and Development 109


Example: Anonymous Function
let numbers = [10, 20, 30, 40, 50];
let squareNumbers = [Link](function(number)
{
return number * number;
});

Grade-11 Web Design and Development 110


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

Grade-11 Web Design and Development 111


Example: Arrow Function
let square = num => num * num;
let result = square(5);
[Link](result); //25

Grade-11 Web Design and Development 112


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.

Example: Nested Functions


function greet(firstName)
{
function SayHello() {
alert("Hello " + firstName);
}
return SayHello();
}
greet("Abebe");

Grade-11 Web Design and Development 113


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!";
}

Grade-11 Web Design and Development 114


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:

Arrow Functions Return Value by Default:


hello = () => "Hello World!";
Note: This works only if the function has only one statement.

Grade-11 Web Design and Development 115


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.

Grade-11 Web Design and Development 116


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

Grade-11 Web Design and Development 117


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.
Grade-11 Web Design and Development 118
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. 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

Grade-11 Web Design and Development 119


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

Grade-11 Web Design and Development 120


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.

Grade-11 Web Design and Development 121


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.

Grade-11 Web Design and Development 122


Example: Return value from a Function
function Sum(num1, num2) {
return num1 + num2;
};
var result = Sum(10,20); // returns 30
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
Grade-11 Web Design and Development 123
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

Grade-11 Web Design and Development 124


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.

Grade-11 Web Design and Development 125


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

Grade-11 Web Design and Development 126


• 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

Grade-11 Web Design and Development 127


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

Grade-11 Web Design and Development 128


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

Grade-11 Web Design and Development 129


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

Grade-11 Web Design and Development 130


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

Grade-11 Web Design and Development 131


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"

Grade-11 Web Design and Development 132


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

The mathematical operators < and > compare two strings and return a
Boolean (true or false) based on the order of the characters in the
string.
The == operator compares the content of strings and === compares
the reference equality of strings.

The localeCompare() method compares two strings in the current


locale. It returns 0 if strings are equal, else returns 1

Grade-11 Web Design and Development 133


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

Grade-11 Web Design and Development 134


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.

Grade-11 Web Design and Development 135


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.

Grade-11 Web Design and Development 136


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.

Grade-11 Web Design and Development 137


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

Grade-11 Web Design and Development 138


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

Grade-11 Web Design and Development 139


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

Grade-11 Web Design and Development 140


Accessing and Modifying DOM Elements:
Change element content, styles, attributes, and more using JavaScript
methods. Create 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.

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"]
Grade-11 Web Design and Development 141
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

Grade-11 Web Design and Development 142


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. 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
Grade-11 Web Design and Development 143
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]);

Grade-11 Web Design and Development 144


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.

Grade-11 Web Design and Development 145


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

Grade-11 Web Design and Development 146


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

Grade-11 Web Design and Development 147


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

Grade-11 Web Design and Development 148


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

Grade-11 Web Design and Development 149


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

Grade-11 Web Design and Development 150


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:
onclick=JavaScript

Grade-11 Web Design and Development 151


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

Grade-11 Web Design and Development 152


In this example, the content of the <h1> element is changed when a user clicks on it:
Example
<!DOCTYPE html>
<html>
<body>
<h1 onclick="[Link] = '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 onclick="changeText(this)">Click on this text!</h1>
<script>
function changeText(id) {
[Link] = "Ooops!";
}
</script>
</body>
</html>

Grade-11 Web Design and Development 153


HTML Event Attributes
To assign events to HTML elements you can use event attributes.
Example
Assign an onclick event to a button element:
<button onclick="displayDate()">Try 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").onclick = displayDate;
</script>

Grade-11 Web Design and Development 154


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.

Grade-11 Web Design and Development 155


The onload and onunload events can be used to deal with cookies.
Example
<body onload="checkCookies()">
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" oninput="upperCase()">

Grade-11 Web Design and Development 156


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“ onchange="upperCase()">

Grade-11 Web Design and Development 157


Grade-11 Web Design and Development 158
UNIT 3
VALIDATING USER INPUT

Grade-11 Web Design and Development 159


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

Grade-11 Web Design and Development 160


[Link] 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 trai

Grade-11 Web Design and Development 161


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.
Validation can be performed on various types of user input,
such as text fields, checkboxes, radio buttons, dropdowns,
and file uploads.

Grade-11 Web Design and Development 162


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

Grade-11 Web Design and Development 163


<form id="myForm" onsubmit="validateForm(event)">

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

Grade-11 Web Design and Development 164


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

return false; // Stop form submission


}
// Additional validation logic for email format, password requirements, etc.
// Form is valid, submit it
[Link]("myForm").submit();
}
Grade-11 Web Design and Development 165
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:

Grade-11 Web Design and Development 166


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>

Grade-11 Web Design and Development 167


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

Grade-11 Web Design and Development 168


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

Grade-11 Web Design and Development 169


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>

Grade-11 Web Design and Development 170


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]) {
[Link](); // Prevent form submission if password and confirm password do not
match
alert("Passwords do not match!");
}
});

Grade-11 Web Design and Development 171


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

Grade-11 Web Design and Development 172


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

Grade-11 Web Design and Development 173


Grade-11 Web Design and Development 174

You might also like