You Can Use JavaScript Object for More Information About an Error
You Can Use JavaScript Object for More Information About an Error
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
In instanceOf typeOf
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.
Keyword Description
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.
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
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
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