Chapter Four Part Two
Client Side Scripting (JavaScript)
November 3, 2025 Leweyehu Y, Mekdela Amba University 1
JavaScript Structures & Data
• In JavaScript, a primitive (primitive value, primitive data type) is data
that is not an object and has no methods or properties.
• There are 7 primitive data types: string, number, bigint, Boolean,
undefined, symbol, null.
• Most of the time, a primitive value is represented directly at the lowest
level of the language implementation.
• All primitives are immutable; that is, they cannot be altered. It is
important not to confuse a primitive itself with a variable assigned a
primitive value.
• The variable may be reassigned to a new value, but the existing value
can not be changed in the ways that objects, arrays, and functions can be
altered
November 3, 2025 Leweyehu Y, Mekdela Amba University 2
JavaScript Primitives Types
• string – A sequence of characters that represent a text value. For
example: "Howdy".
• number -An integer or floating point number. For example: 42 or
3.14159.
• bigint - BigInt is a numeric data type that can represent integers in the
arbitrary precision format. Which may be bigger than 64-bit floating
point.
• In other programming languages different numeric types can exist, for
examples: Integers, Floats, Doubles, or Bignums.
• let x = BigInt("123456789012345678901234567890");
• Boolean - Has value of either true or false.
November 3, 2025 Leweyehu Y, Mekdela Amba University 3
JavaScript Primitives Types
• null - A special keyword denoting a null value. Null is empty/non-
existing value. Null must be assigned, var a = null;
• undefined - Whereas, Undefined most typically means a variable has
been declared, but not defined.
• Var a; [Link](a); //Undefined
• In JavaScript there are only six falsy values. Both null and undefined are
two of the six falsy values. Here’s a full list:
• False, 0 (zero), “” (empty string), null, undefined, NaN (Not A Number)
• The others are truthy, and has real values.
November 3, 2025 Leweyehu Y, Mekdela Amba University 4
JavaScript Data Type Conversion
JavaScript is a dynamically typed language.
This means you don't have to specify the data type of a variable when you declare it.
It also means that data types are automatically converted as-needed during script
execution.
let answer = 42;
answer = 'Thanks!’;
Converting numeric values to string using + sign
In expressions involving numeric and string values with the + operator, JavaScript
converts numeric values to strings.
x = 'The answer is ' + 42; // "The answer is 42“
z = '37' + 7 // "377"
November 3, 2025 Leweyehu Y, Mekdela Amba University 5
JavaScript Data Type Conversion
Converting String to Number
In the case that a value representing a number is in memory as a string, there are
methods for conversion.
parseInt() & parseFloat() - parseInt only returns whole numbers, so its use is
diminished for decimals.
parseInt('101', 2) // 5
An alternative method of retrieving a number from a string is
with the + (unary plus) operator:
[Link](+'54.2’); //the result is 54.2 which is a number.
The + should come first.
November 3, 2025 Leweyehu Y, Mekdela Amba University 6
JavaScript Object Types (Object, Arrays, Dates …)
• In JavaScript, objects can be seen as a collection of properties.
• With the object literal syntax, a limited set of properties are initialized;
then properties can be added and removed.
• Property values can be values of any type, including other objects,
which enables building complex data structures.
• Properties are identified using key values.
• A key value is either a String value or a Symbol value.
• Objects are variables too. But objects can contain many values.
• E.g., let car = "Fiat";
• Or const car = {type:"Fiat", model:"500", color:"white"};
November 3, 2025 Leweyehu Y, Mekdela Amba University 7
JavaScript Object Type
• In JavaScript,
• The values are written as name: value pairs (name and value separated
by a colon).
• const person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};
• Accessing Object’s properties: [Link] and
objectName["propertyName"]
November 3, 2025 Leweyehu Y, Mekdela Amba University 8
JavaScript Object Type
• In JavaScript, Object can have methods – action to be performed on the
object.
• const person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return [Link] + " " + [Link];
}
};
• this – represents current context/object’s.
November 3, 2025 Leweyehu Y, Mekdela Amba University 9
JavaScript Object Type
In methods can be accessed through [Link]()
Accessing method without (), will return method definition,
not the result.
November 3, 2025 Leweyehu Y, Mekdela Amba University 10
JavaScript Array Literals
An array literal is a list of zero or more expressions, each of
which represents an array element, enclosed in square
brackets ([]).
When you create an array using an array literal, it is
initialized with the specified values as its elements, and its
length is set to the number of arguments specified.
const coffees = ['French Roast', 'Colombian', 'Kona'];
Extra commas, const fish = ['Lion', , 'Angel'];
[Link](fish); // [ 'Lion', <1 empty item>, 'Angel' ]
November 3, 2025 Leweyehu Y, Mekdela Amba University 11
JavaScript Array Literals
Only extra comma (one comma) at the end will be ignored.
const myList = ['home', , 'school', ]; //array length is 3
const myList = [, 'home', , 'school’]; //array length is 4
In the following example, the length of the array is four, and
myList[0] and myList[2] are missing.
const myList = ['home', , 'school', , ]; //array length is 4
November 3, 2025 Leweyehu Y, Mekdela Amba University 12
JavaScript Array Literals
Empty Array;
const array = [];
array[0] = 3;
array[1] = 4;
Using new keyword;
const array = new Array(2, 3, 4, 5);
NB: Create array object, avoid using new keyword for simplicity and fast
execution.
Array can have different types of elements at once.
November 3, 2025 Leweyehu Y, Mekdela Amba University 13
JavaScript Array Literals
Methods in Array:
Use push to add element at the end, use pop to remove
element from the end. [Link](), [Link](something)
Use unshift(), to add element to the beginning by shifting
other elements to the right, whereas shift() removes elements
from the beginning and shift all others to next index.
More methods: length,sort(),concat(),splice(), slice()
November 3, 2025 Leweyehu Y, Mekdela Amba University 14
JavaScript String Literals
String literals can be specified using single or double
quotes, which are treated identically, or using the backtick
character
Whereas, the String object is used to represent and
manipulate a sequence of characters.
November 3, 2025 Leweyehu Y, Mekdela Amba University 15
JavaScript String Literals
const string1 = "A string primitive";
const string2 = "Also a string primitive";
const string4 = new String("A String object");
There are two ways to access an individual character in a
string:
• "cat".charAt(1); // gives value "a"
• "cat"[1]; // gives value "a"
When using bracket notation for character access, attempting
to delete or assign a value to these properties will not succeed.
November 3, 2025 Leweyehu Y, Mekdela Amba University 16
JavaScript String Literals: String Methods
String length String trim()
String slice()
String substring()
String trimStart()
String substr() String trimEnd()
String replace() String padStart()
String replaceAll() String padEnd()
String toUpperCase()
String toLowerCase() String charAt()
String concat() String charCodeAt()
String split()
November 3, 2025 Leweyehu Y, Mekdela Amba University 17
Arithmetic & Logical Operators
• Operators
1. Arithmetic Operators
2. Assignment Operators
3. Comparison Operators
4. Logical Operators
5. Conditional Operators
6. Type Operators
November 3, 2025 Leweyehu Y, Mekdela Amba University 18
Arithmetic Operators
November 3, 2025 Leweyehu Y, Mekdela Amba University 19
Assignment Operators
November 3, 2025 Leweyehu Y, Mekdela Amba University 20
Comparison Operator
Mind the ternary operator:
It is called conditional operator.
The only operator with three
Operands.
(3==4)? True : False;
November 3, 2025 Leweyehu Y, Mekdela Amba University 21
Comparison Operator: ternary operator
It can be an alternative to if…else conditioning.
condition ? exprIfTrue : exprIfFalse
Or if (condition)
do this
Else
do this
Also condition chaining
function example() {
return condition1 ? value1
: condition2 ? value2
: condition3 ? value3
: value4;
}
November 3, 2025 Leweyehu Y, Mekdela Amba University 22
Logical Operator
• If ((a==3) && (b==5))
• Do this
November 3, 2025 Leweyehu Y, Mekdela Amba University 23
Reading Assignment
JavaScript Bitwise Operators
November 3, 2025 Leweyehu Y, Mekdela Amba University 24
Control Structures: Conditional Statements
• A conditional statement is a set of commands that executes if a
specified condition is true. JavaScript supports two conditional
statements: if...else and switch
if … else statement
• Use the if statement to execute a statement if a logical condition is true.
Use the optional else clause to execute a statement if the condition is
false.
if (condition) {
statement1;
} else {
statement2;
}
November 3, 2025 Leweyehu Y, Mekdela Amba University 25
Control Structures: Conditional Statements
• You can also compound the statements using else if to have multiple
conditions tested in sequence.
if (condition1) {
statement1;
} else if (condition2) {
statement2;
} else if (conditionN) {
statementN;
} else {
statementLast;
}
November 3, 2025 Leweyehu Y, Mekdela Amba University 26
Control Structures: Conditional Statements
• Tips
1. Simplify
Var x = false;
If (x == true) {//when true}
• Just say if (x) {//when true}
2. Use block statements ({}), especially when nesting if .. Else
3. Remember Falsy Literals? Refer back
4. Remember, === may not be equal with ==
November 3, 2025 Leweyehu Y, Mekdela Amba University 27
Control Structures: Conditional Statements
• Switch Statements
• A switch statement allows a program to evaluate an expression and
attempt to match the expression's value to a case label.
• If a match is found, the program executes the associated statement.
switch (expression) {
case label1:
statements1; break;
default:
statementsDefault;
}
November 3, 2025 Leweyehu Y, Mekdela Amba University 28
Control Structures: Conditional Statements
• The program first look for case clause. If no matching case found, it
continue looking for default case.
• If default does not exist, it will get out of switch, and continue to next
statements right after switch.
• If case found, it will execute that case and look for case break. If no
break found, it continue executing the next case without condition, until
it found another break.
• NB: don’t forget to put break, after each cases.
• adding default is also nice approach. Default doesn't require break
statement if it comes at last.
November 3, 2025 Leweyehu Y, Mekdela Amba University 29
If…else Vs Switches ?
• The if-else statement checks for equality as well as for logical expression. On the other hand, switch checks only
for equality.
• The if statement evaluates integer, character, pointer or floating-point type or boolean type. On the other hand,
switch statement evaluates only character or an integer datatype.
• Sequence of execution is like either statement under if block will execute or statements under else block
statement will execute. However, the expression in the switch statement decides which case to execute and if
you do not apply a break statement after each case it will execute till the end of switch statement.
• For an if-else statement, if the expression inside of the if turn outs to be false, the statement inside of the else
block will be executed. For the switch statement, if the expression inside of the switch statement turns out to be
false then the default statements are executed.
• It’s known to be difficult to edit if-else statements since it’s tedious to trace where the correction is required.
Many people agree that it’s much simpler to edit switch statements since they’re easy to trace.
• A switch statement works much faster than an equivalent if-else ladder. It’s because the compiler generates a
jump table for a switch during compilation. As a result, during execution, instead of checking which case is
satisfied, it only decides which case has to be executed.
• It’s more readable compared to if-else statements.
November 3, 2025 Leweyehu Y, Mekdela Amba University 30
Control Structures: Conditional Statements
•Reading Assignment Try Catch
November 3, 2025 Leweyehu Y, Mekdela Amba University 31
JavaScript Loops & Iterations
• Loops offer a quick and easy way to do something repeatedly. There are many
different kinds of loops, but they all essentially do the same thing: they repeat an
action some number of times.
• For statement
• A for loop repeats until a specified condition evaluates to false. The JavaScript for loop
is similar to the Java and C for loop.
• for ([initialExpression]; [conditionExpression]; [incrementExpression])
statement
• Initialize once, check conditions - then if true execute statement,
increment, then check condition again.
• In case conditionexpression not exist, evaluation is always true.
November 3, 2025 Leweyehu Y, Mekdela Amba University 32
JavaScript Loops & Iterations
• The do...while statement repeats until a specified condition evaluates to
false.
do
statement
while (condition);
• Statement is always executed once before the condition is checked.
let i = 0;
do {
i += 1;
[Link](i);
} while (i < 5);
November 3, 2025 Leweyehu Y, Mekdela Amba University 33
JavaScript Loops & Iterations
• A while statement executes its statements as long as a specified condition evaluates to
true.
while (condition)
statement
• If the condition becomes false, statement within the loop stops executing and control
passes to the statement following the loop.
let n = 0;
let x = 0;
while (n < 3) {
n++;
x += n;
}
November 3, 2025 Leweyehu Y, Mekdela Amba University 34
JavaScript Iterations
• The for…in statement
• The for...in statement iterates a specified variable over all the
enumerable properties of an object.
for (variable in object)
statement
//can display all properties of car array, or object
for (property in car)
[Link](car[property]);
//it is better to use tradition for loop for iterating over array
November 3, 2025 Leweyehu Y, Mekdela Amba University 35
JavaScript Iterations
• The for…of statement
• The for...of statement creates a loop Iterating over iterable objects
(including Array, Map, Set, arguments object and so on), invoking a
custom iteration hook with statements to be executed for the value of
each distinct property.
for (variable of object)
statement
• for...in iterates over property names, for...of iterates over property values.
• The for...of and for...in statements can also be used with destructuring.
• For example, you can simultaneously loop over the keys and values of an
object using [Link]().
November 3, 2025 Leweyehu Y, Mekdela Amba University 36
Cont.
const obj = { foo: 1, bar: 2 };
for (const [key, val] of [Link](obj)) {
[Link](key, val);
}
// "foo" 1
// "bar" 2
November 3, 2025 Leweyehu Y, Mekdela Amba University 37
JavaScript Function
• Functions are one of the fundamental building blocks in JavaScript. A function in
JavaScript is similar to a procedure.
• A function definition (also called a function declaration, or function statement) consists
of the function keyword, followed by function name, parameters, enclosed block and
return/if exists.
function square(number) {
return number * number;
}
• Parameters are essentially passed to functions by value.
• When you pass an object/array as a parameter, if the function changes
the object's properties, that change is visible outside the function.
November 3, 2025 Leweyehu Y, Mekdela Amba University 38
JavaScript Function
function myFunc(theArr) {
theArr[0] = 30;
}
const arr = [45];
[Link](arr[0]); // 45
myFunc(arr);
[Link](arr[0]); // 30
November 3, 2025 Leweyehu Y, Mekdela Amba University 39
Function Expression
• The function keyword can be used to define a function inside an
expression.
• Such a function can be anonymous; it does not have to have a name. For
example, the function square could have been defined as:
const square = function (number) {
return number * number;
}
const x = square(4); // x gets the value 16
November 3, 2025 Leweyehu Y, Mekdela Amba University 40
Function declaration vs function expression:
There are two ways of defining/declaring a function, we can either use a
function declaration or a function expression.
Function declaration: Syntax for defining function with declaration
November 3, 2025 Leweyehu Y, Mekdela Amba University 41
Call/invoking a function in JavaScript using
the call() method
The code inside a function is not executed when the function is defined.
The code inside any JavaScript function will execute only when
"something" invokes it.
It is common to use the term "call a function", "invoke a function", "start a
function, "start a function, all to mean execute the function.
See below how we can call/invoke the above example function:
•myFunctionName(11, 10); // returns 21 because of 11 + 10
Function expressions: Syntax for defining function with
declaration
November 3, 2025 Leweyehu Y, Mekdela Amba University 42
Functions with arguments
Function parameters: Some functions take inputs to successfully
perform their task.
The input we give to our function is called "parameter".
Function parameters are the names/variables given when we
define/create the function.
They are just values we supply to the function so that the function can do
something utilizing those values.
November 3, 2025 Leweyehu Y, Mekdela Amba University 43
Functions Cont’d…
Note: Functions can be declared wihtout parametes as well
Function arguments: Arguments are the actual value of the parameter passed
to and received by the function.
Arguments are values we supply when we call/use/invoke a function.
Example: When we invoke the myFunction function above, we will need to pass
an argument like this:
November 3, 2025 Leweyehu Y, Mekdela Amba University 44
Arrow functions
Arrow functions were introduced in ES6. An arrow function is an
alternative to a traditional function expression but is limited and
can't be used in all situations.
Arrow functions allow us to write shorter function syntax.
Syntax: const myFunction = (a, b) => a * b;
November 3, 2025 Leweyehu Y, Mekdela Amba University 45
Arrow function vs traditional function
November 3, 2025 Leweyehu Y, Mekdela Amba University 46
JavaScript DOM
• The Document Object Model (DOM) is the data representation of the
objects that comprise the structure and content of a document on the
web.
• The Document interface represents any web page loaded in the browser
and serves as an entry point into the web page's content
• The Document Object Model (DOM) is a programming interface for web
documents.
• It represents the page so that programs can change the document
structure, style, and content.
• The DOM represents the document as nodes and objects; that way,
programming languages can interact with the page.
November 3, 2025 Leweyehu Y, Mekdela Amba University 47
JavaScript DOM
• As an object-oriented representation of the web page,
it can be modified with a scripting language such as
JavaScript.
• Example
const paragraphs = [Link]("p");
// paragraphs[0] is the first <p> element
// paragraphs[1] is the second <p> element, etc.
alert(paragraphs[0].nodeName);
• All of the properties, methods, and events available for
manipulating and creating web pages are organized into
objects.
November 3, 2025 Leweyehu Y, Mekdela Amba University 48
JavaScript DOM
• The DOM is not a programming language, but without it, the
JavaScript language wouldn't have any model or notion of web
pages, HTML documents, and more.
• The DOM is not part of the JavaScript language, but is
instead a Web API used to build websites.
• The DOM was designed to be independent of any particular
programming language, making the structural representation of
the document available from a single, consistent API.
November 3, 2025 Leweyehu Y, Mekdela Amba University 49
Accessing HTML Elements
• A DOM tree is a kind of tree whose nodes represent an HTML or XML document's
contents. Each HTML or XML document has a unique DOM tree representation.
• For example, the following document and document tree.
November 3, 2025 Leweyehu Y, Mekdela Amba University 50
Accessing HTML Elements
• In the DOM, all HTML elements are defined as objects. The programming interface is
the properties and methods of each object.
• A property is a value that you can get or set (like changing the content of an HTML
element). A method is an action you can do (like add or deleting an HTML element).
<html>
<body>
<p id="demo"></p>
<script>
[Link]("demo").innerHTML = "Hello World!";
</script>
</body>
</html>
getElementById is a method, while innerHTML is a property
November 3, 2025 Leweyehu Y, Mekdela Amba University 51
Accessing HTML Elements
• Several ways to access elements
• Finding HTML elements by id
• Finding HTML elements by tag name
• Finding HTML elements by class name
• Finding HTML elements by CSS selectors
• Finding HTML elements by HTML object collections
November 3, 2025 Leweyehu Y, Mekdela Amba University 52
Accessing HTML Elements
• Finding HTML elements by id
const element = [Link](“myPara”);
This return element as an object if found this id, else
return null.
Finding HTML elements by tag name
const element = [Link]("p");
const x = [Link]("main");
const y = [Link]("p");
November 3, 2025 Leweyehu Y, Mekdela Amba University 53
Accessing HTML Elements
• Finding HTML elements by Class Name
const x = [Link]("intro");
Returns collection of object if class name found else
empty object
Finding HTML elements by CSS selectors
querySelector(selectors)
querySelectorAll(selectors)
const x = [Link]("[Link]");
November 3, 2025 Leweyehu Y, Mekdela Amba University 54
Accessing HTML Elements
• Finding HTML elements by HTML object collections
The HTMLCollection interface represents a generic
collection (array-like object similar to arguments) of
elements (in document order) and offers methods and
properties for selecting from the list.
E.g. [Link] return all list of images in document
Some Instances
[Link]
[Link]()
[Link]()
November 3, 2025 Leweyehu Y, Mekdela Amba University 55
Accessing HTML Elements
• Finding HTML elements by HTML object collections: most
common
November 3, 2025 Leweyehu Y, Mekdela Amba University 56
Accessing HTML Elements
• Changing HTML element content
• Using innerHTML
• [Link](id).innerHTML
• Changing HTML Element Attribute
• Using attribute
• [Link](id).attribute
November 3, 2025 Leweyehu Y, Mekdela Amba University 57
Accessing CSS/styles
The HTML DOM allows JavaScript to change the style of HTML
elements.
[Link](id).[Link]
Allows us to access style property of an element with the
given ID
Changing is style is also simple:
[Link](id).[Link] = new
property
November 3, 2025 Leweyehu Y, Mekdela Amba University 58
Event Handling in JS
Events are fired to notify code of "interesting changes" that may affect
code execution.
These can arise from user interactions such as using a mouse or
resizing a window, changes in the state of the underlying
environment.
Each event is represented by an object that is based on the Event
interface, and may have additional custom fields and/or functions to
provide information about what happened.
A JavaScript can be executed when an event occurs, like when a user
clicks on an HTML element.
November 3, 2025 Leweyehu Y, Mekdela Amba University 59
Event Handling in JS
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
November 3, 2025 Leweyehu Y, Mekdela Amba University 60
Event Handling in JS
Events like:
onclick
onchange
onmouseover / onmouseout
Onmousedown / onmouseup
onfocus
For example
<input type=“text” name=“fname”>
<script>
function focused(x){ var value = [Link];}
</script>
November 3, 2025 Leweyehu Y, Mekdela Amba University 61
Event Handling in JS
Adding Event Listener
Using addEventListener()
[Link](event, function); //function here is
callback function name or anonymous.
E.g. [Link]("click", myFunction);
There,
function myFunction(){
//do something here
}
//[Link](“click", myFunction); will remove attached event.
November 3, 2025 Leweyehu Y, Mekdela Amba University 62
JavaScript Form Processing
• Event onsubmit
• If onsubmit returned false, the form won’t be sent to server
• Else form will be sent to server/processing
• Form Validation
Server side validation is performed by a web server, after input has been sent to the
server.
Client side validation is performed by a web browser, before input is sent to a web server.
• Or using HTML5 input attribues: like max, required, type,
pattern, (READ FOR MORE)…
November 3, 2025 Leweyehu Y, Mekdela Amba University 63
JavaScript Form Processing
<form id="form1" validate()" action="">
<input type="text" name="name">
<input type="submit" name="submit">
</form>
function validate() {
var v = [Link]['form1']['name’].value
if (v == "")
return false;
}
November 3, 2025 Leweyehu Y, Mekdela Amba University 64
JavaScript BOM
The Browser Object Model (BOM) allows JavaScript to "talk to" the
browser.
Like window, Screen, Location, History, Navigator, Cookies, Timing and
more.
The window object
The window object is supported by all browsers. It represents the
browser's window.
All global JavaScript objects, functions, and variables automatically
become members of the window object.
Global variables are properties of the window object. Global
functions are methods of the window object.
November 3, 2025 Leweyehu Y, Mekdela Amba University 65
JavaScript BOM
Window sizing: Two properties can be used to determine the size of the
browser window.
Example
[Link] - the inner height of the browser window (in
pixels)
[Link] - the inner width of the browser window (in
pixels)
innerHeight – the height of browser, without tabs/closing buttons. But
includes scrollbar. Likewise innerWidth.
November 3, 2025 Leweyehu Y, Mekdela Amba University 66
JavaScript BOM
Window sizing: Two properties can be used to determine the size of the
browser window.
[Link]() - open a new window
[Link]() - close the current window
You can open new window with these features
open()
open(url)
open(url, target)
open(url, target, windowFeatures)
E.g. This will open a new popup window with google page url
[Link]('[Link] '_blank', 'popup=yes')
November 3, 2025 Leweyehu Y, Mekdela Amba University 67
JavaScript BOM
Window sizing: Two properties can be used to determine the size of the
browser window.
[Link]()
[Link](): returns true if ok and false if cancled
[Link](‘msg’,’default msg’): get user inputs
November 3, 2025 Leweyehu Y, Mekdela Amba University 68
End of Chapter
November 3, 2025 Leweyehu Y, Mekdela Amba University 69