0% found this document useful (0 votes)
4 views

You Can Use JavaScript Object for More Information About an Error

The document provides an overview of JavaScript syntax and basic concepts, including variable declaration, data types, and operators. It explains how to write JavaScript code, the importance of case sensitivity, and the use of comments. Additionally, it covers variable scope, dynamic typing, and various operators used in JavaScript programming.

Uploaded by

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

You Can Use JavaScript Object for More Information About an Error

The document provides an overview of JavaScript syntax and basic concepts, including variable declaration, data types, and operators. It explains how to write JavaScript code, the importance of case sensitivity, and the use of comments. Additionally, it covers variable scope, dynamic typing, and various operators used in JavaScript programming.

Uploaded by

samuel asefa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 59

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, Node.js is a framework based on JavaScript that executes on
the server.
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;
</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 one = 1; 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 one =1;
var one = 1;
var one = 1;
</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 one =1; // this is a single line comment
/* this
is multi line
comment*/
var two = 2;
var three = 3;
</script>
String: A string is a text in JavaScript. The text content must be enclosed in double or single
quotation marks.
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>
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.
2.2.1.1 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.
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
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 typea 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
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'};
person.name = "Bill";
alert(person.name); //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!";
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.
Grade 11 Web Design and Development Student Module
Ministry of Education 600
2.1.1.2 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:
document.getElementById("myH").innerHTML = "My First Page";
// Change paragraph:
document.getElementById("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"
Grade 11 Web Design and Development Student Module
Ministry of Education 601
in my web page:
*/
document.getElementById("myH").innerHTML = "My First Page";
document.getElementById("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
//document.getElementById("myH").innerHTML = "My First Page";
document.getElementById("myP").innerHTML = "My first paragraph.";
This example uses a comment block to prevent execution of multiple lines:
Example
/*
document.getElementById("myH").innerHTML = "My First Page";
document.getElementById("myP").innerHTML = "My first paragraph.";
*/
2.1.1.3 Javascript Operators
JavaScript includes operators same as other languages. An operator performs some operation
on single or multiple operands (data value) and produces a result. For example, in 1 + 2, the + sign is an
operator and 1 is left side operand and 2 is right side operand. The + operator performs the addition of
two numeric values and returns a result. JavaScript includes following categories of operators.
1. Arithmetic Operators
2. Comparison Operators
3. Logical Operators
4. Assignment Operators
5. Conditional Operators
6. Ternary Operator
Arithmetic Operators
Arithmetic operators are used to perform mathematical operations between numeric operands.
Operator Description
+ 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
Grade 11 Web Design and Development Student Module
Ministry of Education 603
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
Grade 11 Web Design and Development Student Module
Ministry of Education 604
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 rightside
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
Grade 11 Web Design and Development Student Module
Ministry of Education 605
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 nonzero;
otherwise, returns 0.
|| || is known as OR operator. It checks whether any one of the two operands is nonzero
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.
Grade 11 Web Design and Development Student Module
Ministry of Education 606
Assignment
operators
Description
= 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.
Grade 11 Web Design and Development Student Module
Ministry of Education 607
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.
2.1.1.4 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 Student Module
Ministry of Education 608
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.
Grade 11 Web Design and Development Student Module
Ministry of Education 609
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.
Grade 11 Web Design and Development Student Module
Ministry of Education 610
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
document.getElementById("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
Grade 11 Web Design and Development Student Module
Ministry of Education 611
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.
Grade 11 Web Design and Development Student Module
Ministry of Education 612
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;
Grade 11 Web Design and Development Student Module
Ministry of Education 613
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..
}
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)
{
Grade 11 Web Design and Development Student Module
Ministry of Education 615
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.
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++)
{
console.log(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;
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++)
{
console.log(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;
console.log(arr[i]);
i++;
}
Output:
10 11 12 13 14
Learn about while loop in the next section.
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.
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
document.getElementById("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:
Example
function myFunction() {
document.getElementById("demo1").innerHTML = "Hello Dolly!";
document.getElementById("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
}
• 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)
{
document.getElementById("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.
The finally block executes regardless of whatever happens.
Example: finally Block
try
{
var result = Sum(10, 20); // Sum is not defined yet
}
catch(ex)
{
document.getElementById("errorMessage").innerHTML = ex;
}
finally{
document.getElementById("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);
}
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(ex.number + "- " + ex.message);
}

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

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

unctions 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.
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 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 = numbers.map(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);
console.log(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.
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:
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.
Example
With a regular function this represents the object that calls the function:
// Regular Function:
hello = function() {
document.getElementById("demo").innerHTML += this;
}
// The window object calls the function:
window.addEventListener("load", hello);
// A button object calls the function:
document.getElementById("btn").addEventListener("click", hello);
Example
With an arrow function this represents the owner of the function:
// Arrow Function:
hello = () => {
document.getElementById("demo").innerHTML += this;
}
// The window object calls the function:
window.addEventListener("load", hello);
// A button object calls the function:
document.getElementById("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.
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.
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();
console.log(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
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.
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 str.at(pos) method.
Example: String as array
let str = 'Hello World';
let ch1 = str[0] // H
let ch2 = str[1] // e
let ch3 = str.at(2) // l
let ch4 = str.at(3) // l
str[4] = "P"; //error
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< str.length; i++)
console.log(str[i]);
for(let ch of str)
console.log(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';
String Concatenation
JavaScript string can be concatenated using the + operator or string.concat() method.
Example: String concatenation
let str1 = 'Hello ';
let str2 = "World ";
let str3 = str1 + str2; //Hello World
let str4 = str1.concat(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 string.localeCompare(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.
Example: String Comparison
console.log("a" < "b"); //true
console.log("b" < "a"); //false
console.log("Apple" == "Apple"); //true
console.log("Apple" == "apple"); //false
console.log("Apple" === "Apple"); //true
console.log("Apple" === "apple"); //false
console.log("Apple".localeCompare("Apple")); //0
console.log("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');
console.log(str1 == str2); //true
console.log(str1 === str2);//true
console.log(str1 == str3); //true
console.log(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.

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.
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"];
console.log(cities.length); //4
cities[4] = "Delhi";
console.log(cities.length); //5
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";
console.log(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];
console.log(numArr[0]); // 10
console.log(numArr[1]); // 20
console.log(numArr[2]); // 30
console.log(numArr[3]); // 40
console.log(numArr[4]); // 50
let cities = ["Addis_Ababa", "New York", "Paris", "Sydney"];
console.log(cities[0]); // "Addis_Ababa"
console.log(cities[1]); // "New York"
console.log(cities[2]); // "Paris"
console.log(cities[3]); // "Sydney"
//accessing element from nonexistance index
console.log(cities[4]); // undefined
For the new browsers, you can use the arr.at(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];
console.log(numArr.at(0)); // 10
console.log(numArr.at(1)); // 20
console.log(numArr.at(2)); // 30
console.log(numArr.at(3)); // 40
console.log(numArr.at(4)); // 50
console.log(numArr.at(5)); // undefined
//passing negative index
console.log(numArr.at(-1)); // 50
console.log(numArr.at(-2)); // 40
console.log(numArr.at(-3)); // 30
console.log(numArr.at(-4)); // 20
console.log(numArr.at(-5)); // 10
console.log(numArr.at(-6)); // undefined
You can iterate an array using Array.forEach(), for, for-of, and for-in loop, as shown below.
Example: Accessing Array Elements
let numArr = [10, 20, 30, 40, 50];
numArr.forEach(i => console.log(i)); //prints all elements
for(let i=0; i<numArr.length; i++)
console.log(numArr[i]);
for(let i of numArr)
console.log(i);
for(let i in numArr)
console.log(numArr[i]);
Grade 11 Web Design and Development Student Module
Ministry of Education 640
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
console.log(cities); //["Addis_Ababa", "New York", "Paris", "Sydney", "Delhi"]
cities[cities.length] = "London";//use length property to specify last index
console.log(cities); //["Addis_Ababa", "New York", "Paris", "Sydney", "Delhi", "London"]
cities[9] = "Pune";
console.log(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"];
cities.push("Delhi"); //add new element at last
console.log(cities); //["Addis_Ababa", "New York", "Paris", "Sydney", "Delhi"]
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"];
cities.unshift("Delhi"); //adds new element at the beginning
console.log(cities); //["Delhi", "Addis_Ababa", "New York", "Paris", "Sydney"]
cities.unshift("London", "Pune"); //adds new element at the beginning
console.log(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 = cities.pop(); //returns and removes the last element
console.log(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 = cities.shift(); //returns first element and removes it from array
console.log(cities); //["New York", "Paris", "Sydney"]
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 = cities.filter(function(item) {
return item !== cityToBeRemoved
})
console.log(mycities); //["Addis_Ababa", "New York", "Sydney"]
console.log(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:
onclick=JavaScript

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

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>
document.getElementById("myBtn").onclick = displayDate;
</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.
Grade 11 Web Design and Development Student Module
Ministry of Education 645
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()">
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()">
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.

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 dowhile
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?
Grade 11 Web Design and Development Student Module
Ministry of Education 647
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
Grade 11 Web Design and Development Student Module
Ministry of Education 648
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

3.1. Validating User Input


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.
• 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" 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>
JavaScript: javascript
function validateForm(event) {
event.preventDefault(); // Prevent form submission
// Get form inputs
var nameInput = document.getElementById("name");
var emailInput = document.getElementById("email");
// Validate name
if (nameInput.value === "") {
alert("Please enter your name.");
return false; // Stop form submission
}
// Validate email
if (emailInput.value === "") {
alert("Please enter your email.");
Grade 11 Web Design and Development Student Module
Ministry of Education 651
return false; // Stop form submission
}
// Additional validation logic for email format, password requirements, etc.
// Form is valid, submit it
document.getElementById("myForm").submit();
}
In this example, the validateForm function is called when the form is submitted. It first prevents
the default form submission using event.preventDefault(). 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 document.getElementById("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="submitForm.php" 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>
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 = document.getElementById("myForm");
form.addEventListener("submit", function(event) {
if (!form.checkValidity()) {
event.preventDefault(); // 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 event.preventDefault() 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.
Example 3: Here's an additional example of form validation in JavaScript using HTML5:
HTML Form Structure:
html
<form id="myForm" action="submitForm.php" 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 = document.getElementById("myForm");
var password = document.getElementById("password");
var confirmPassword = document.getElementById("confirmPassword");
form.addEventListener("submit", function(event) {
if (!form.checkValidity()) {
event.preventDefault(); // Prevent form submission if validation fails
} else if (password.value !== confirmPassword.value) {
event.preventDefault(); // 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 event.preventDefault() 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 serverside
languages/frameworks like PHP, Python (Django/Flask), Ruby (Ruby on Rails), or .NET
(ASP.NET) 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 Student Module
Ministry of Education 655
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
Grade 11 Web Design and Development Student Module
Ministry of Education 656
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
b) Validating email addresses
c) Verifying password strength
d) All of the above
6. What is the purpose of preventing form submission in validation?
a) To display error messages to the
user
b) To clear the form fields
c) To redirect the user to another
page
d) None of the above
Grade 11 Web Design and Development Student Module
Ministry of Education 657

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
Grade 11 Web Design and Development Student Module
Ministry of Education 658

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:
Grade 11 Web Design and Development Student Module
Ministry of Education 659
html
Copy code
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Example</title>
<script src="script.js"></script> <!-- External JavaScript file -->
</head>
<body>
<h1>Hello, world!</h1>
<script>
// Inline JavaScript code
console.log('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)
Grade 11 Web Design and Development Student Module
Ministry of Education 660
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
console.log(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) {
console.log('Number is positive');
} else if (num < 0) {
console.log('Number is negative');
} else {
console.log('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) {
console.log(`Hello, ${name}!`);
}
greet('Alice'); // Hello, Alice!
o Function Expression:
javascript
Copy code
let square = function(x) {
return x * x;
};
console.log(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
console.log(result); // 8
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.
Grade 11 Web Design and Development Student Module
Ministry of Education 663

References
1. Introduction to JavaScript (JS): Crockford, D. (2008). JavaScript: The Good Parts.
O'Reilly Media. Retrieved from https://www.oreilly.com/library/view/javascript-thegood/
9780596517748/JavaScript Events Examples (w3schools.com)
2. JavaScript Syntax and Basic Concepts: Haverbeke, M. (2018). Eloquent JavaScript: A
Modern Introduction to Programming. No Starch Press. Retrieved
from https://eloquentjavascript.net/ for loop in JavaScript (tutorialsteacher.com)
3. Control Structures and Loops: Flanagan, D. (2011). JavaScript:The Definitive
Guide.O'ReillyMedia.Retrieved

You might also like