Ch 20 Programming
Ch 20 Programming
JavaScript allows you to add behavior to your site like responding to user actions, updating
content dynamically and creating animations.
You can add JavaScript to a webpage by writing it inside <script> tags in your HTML file.
Example:
<body>
<script>
alert("Hello world");
</script>
</body>
Displaying output:
Document.write:
The code document.write(the output) will output the text inside the brackets to the web page.
document.write() is a method in JavaScript that allows you to write (or insert) content directly
into the HTML document. This content can be plain text, HTML, or even JavaScript code.
When the document.write() function is called, the content is inserted at the current position
in the document<html>
Page 1 of 46
<body>
<script>
</script>
</body>
.innerHTML:
The .innerHTML property allows you to get or set the HTML content of an element. This
means you can use it to dynamically change the content of any HTML element on your page
without overwriting the entire document. .innerHTML modifies the content of a specific
element on the page without affecting other content.
<body>
<script>
</script>
Page 2 of 46
Pop-up boxes:
1. Alert Box
An alert box is used to display a simple message to the user. The user must click the "OK"
button to dismiss the alert.
alert("Hello world");
or window.alert(“Hello world);
2. Confirm Box
A confirm box has two options: Ok and Cancel. It is often used to confirm an action from the
user.
<script>
if (userResponse) {
alert("Item deleted.");
else {
alert("Action canceled.");
</script>
In this example, if the user confirms, it shows "Item deleted"; if canceled, it shows "Action
canceled".
Page 3 of 46
3. prompt Box
A prompt box allows the user to input data. It displays a text field where the user can type in a
response. It gives them the option of ok and cancel.
<script>
alert("userName ");
</script>
Console.log:
console.log() is designed to log output to the browser's Developer Tools Console for
debugging purposes. It doesn't affect what is displayed on the page itself. This means it doesn't
alter the page's HTML or visual content. Instead, it helps developers track the state of
variables, view error messages, or trace the flow of code execution.
The browser sees that you used console.log(), and it displays the information in the Console
section of its Developer Tools.
Example:
<script>
console.log("Name:", name);
console.log("Age:", age);
</script>
Page 4 of 46
Where to see the logs:
Variables: A variable is a space in memory that is given a name (an identifier), where you can
store data that can change while the program is running. It is like a storage container where
you can keep data (like numbers, text, etc.) and use it later in your program.
Var tells javaScript that you are creating a variable and name is the name of the variable.
• Variable names can include letters, numbers, underscores (_), and dollar signs ($).
Initializing a Variable: When you declare a variable, you can immediately assign it a value using
the = operator. Assigning means adding a value to that variable.
• Example: var age = 25; – This creates a variable named age and sets it to 25.
Data Types:
The data stored in a variable will be of a set data type. Data types are not declared when
declaring a variable; it is assumed when a value is given to the variable.
• String: A sequence of characters & numbers. Any text string must start and end with
either single or double quotation marks, for example ‘…..’ or “……”. (e.g., "Hello",
'JavaScript').
Page 5 of 46
• Boolean: A value that is either true or false.
• Object: A collection of data or a series of named values of the variable (like a person
with a name and age).
• Array: A list of values off the same data type. (e.g., [1, 2, 3]).
Functions
A function is a set of instructions that perform a specific task. It is an independent code that
only runs if it is called.
Functions can be a) called from within the JavaScript code, b) called when an event occurs
such as clicking a button, and automatically run.
2. Processing: It does something with that data (like adding, multiplying, etc.).
3. Output: The function returns a result (a value that you can use later).
All the code that will run in the function needs to be inside the brackets { }.
When you create a function, you can create a variable inside it (local) or outside it (global).
Local Variable:
A local variable is a variable that is defined inside a function. It can only be used within that
function and is not accessible outside of it.
Only accessible inside the function where they are defined. They are "local" to that function.
Exist only as long as the function is running. Once the function finishes, the local variable is
destroyed.
Local Variables are used when you want a variable to be used only within a specific function,
keeping it isolated from the rest of the program.
Page 6 of 46
Global Variable:
A global variable is a variable that is defined outside any function, typically at the top of your
program. It can be accessed and modified from anywhere in your code, including inside
functions.
Accessible throughout the entire program, both inside and outside any function.
Exist for as long as the program runs, and their values can be changed from anywhere.
Global Variables are used when you need a variable to be shared across multiple functions or
parts of your program.
Example:
<script>
function exampleFunction() {
exampleFunction();
</script>
Page 7 of 46
Form elements:
Form elements in JavaScript are HTML elements that allow users to input data. These elements
typically include <input>, <select>, <textarea>, <button>, etc.
You need to tell HTML that you are creating a form using the <form></form> tag.
In JavaScript, you can manipulate these elements to create interactive forms, capture user
input, validate data, and process form submissions.
Button:
When the user clicks on an element, for example an HTML button, it can be programmed to
call a JavaScript function.
<body>
<script>
function showMessage() {
</script>
</body>
Page 8 of 46
Text Input Field (<input type="text">)
The <input> element is used to create interactive fields where the user can type text.
The entered data can be accessed and used. The data is accessed using
document.getElementById( ).value with the textbox identifier in the brackets.
Example:
<body>
<p id="output"></p>
<script>
function showText() {
document.getElementById("output").innerHTML = inputText;
</script>
Dropdown box:
A dropdown box in JavaScript is an HTML element that allows users to select one option from
a list of options. It is created using the <select> element, and the individual options within the
dropdown are represented by the <option> element.
Page 9 of 46
Example:
<body>
<h1>Select a Fruit</h1>
<option value="apple">Apple</option> //if the user selects "Apple" from the dropdown, the
value "apple" is what will be used when submitting the form
<option value="banana">Banana</option>
<option value="cherry">Cherry</option>
<option value="date">Date</option>
</select>
<script>
function displaySelectedFruit() {
</script>
</body>
Page 10 of 46
Radio Button:
Radio buttons are used when the user needs to select one option from multiple choices. They
are commonly used in forms when there are multiple options, but only one selection is
allowed.
Example:
<body>
<h1>Choose a fruit:</h1>
<p id="result"></p>
<script>
function showSelected() {
} }
</script> </body>
Page 11 of 46
Changing images:
You can change or set an image by modifying the src (source) attribute of an <img> element.
• Place image1.jpg and image2.jpg (or any two images you want to use) in the same folder
as your HTML file.
Example:
<body>
<script>
function changeImage() {
image.src = "image2.jpeg";
</script>
Detecting events
Events are actions that occur in the browser or webpage, such as when a user clicks a button,
hovers over an element, submits a form, or presses a key. JavaScript provides ways to detect
these events and trigger specific actions (functions) in response.
You can directly assign event handlers in HTML attributes (like onclick, onmouseover, etc.).
Page 12 of 46
Types of Events:
Mouse Events:
Example:
<body>
<script>
function showMessage(){
alert("Hello World"); }
</script>
</body>
In the below example, when the user puts their cursor over the image, the image will change.
Example:
<body>
<script>
function changeImage(){
document.getElementById("imageHolder").src="image2.jpeg" }
</script> </body>
Page 13 of 46
3. mouseout: Triggered when the mouse pointer leaves an element.
In the below example, when the user moves the cursor away from the image, a different
function is called.
Example:
<body>
<script>
function changeImage1(){
document.getElementById("imageHolder").src="image2.jpeg"
function changeImage2(){
document.getElementById("imageHolder").src="image1.jpg"
</script>
</body>
Page 14 of 46
Keyboard Events:
In the below example, every time the user types a letter a message will output.
<body>
<script>
function outputLetter(){
alert("Letter clicked")
</script>
</body>
Window Events:
load: Triggered when the entire page (including images, scripts, etc.) has finished loading.
When onload is attached to an element, it will run when the element is called or loaded.
Example:
<script>
function outputText(){
alert("Hello World"); }
</script>
</body>
Page 15 of 46
Form Events:
Change event: Onchange is typically used to detect when the value of an input element (like a
text field, checkbox, select dropdown, etc.) changes. This event occurs when the element's
value is modified, and the element loses focus.
In the below example, when the user changes their option in the drop-down box, the function
will called.
<body>
<option> purple</option>
<option> orange</option>
<option> blue</option>
</select>
<script>
function outputText(){
alert("Hello world")
</script>
</body>
Page 16 of 46
Changing HTML styles:
After the name of your element, put the command .style and then the name of the style you
are trying to change, for example, .color, or .fontsize.
Page 17 of 46
Example 1: Changing the Background color
<body>
<script>
function changeBackgroundColor() {
document.body.style.backgroundColor = "lightblue";
</script>
</body>
<body>
<script>
function changeTextStyle() {
textElement.style.color = "green";
textElement.style.fontSize = "48px";
</script>
</body>
Page 18 of 46
Changing Values:
You can change the value stored in a variable after it is declared. To convert data to a string,
use the command String (). To convert data to an integer, use the command Number ().
Example:
<script>
alert(firstName);
alert(lastName);
alert(age);
console.log("Name:", firstName);
console.log("Age:", age);
</script>
Operators:
An operator is a symbol, or set of symbols, that perform an action. JavaScript has a number of
types of operators.
• Arithmetic operators
• string operators
• assignment operators
• comparison operators and logical operators
• conditional operator.
Page 19 of 46
Arithmetic operators:
Example:
<script> document.write(product);
Page 20 of 46
String Operators:
Example:
<script>
document.write("<br><br>");
</script>
Page 21 of 46
Assignment Operators:
Example:
<body> result -= 3;
Page 22 of 46
Comparison and Logical operators:
Comparison operators are used to compare two values. The result of a comparison is always a
boolean value: either true or false.
Logical operators are used to combine multiple boolean expressions and return a boolean
value (true or false).
< Less than Checks if the left operand is less than the right
operand.
<= Less than or equal to Checks if the left operand is less than or equal
to the right operand.
&& Logical AND Returns true if both operands are true.
|| Logical OR Returns true if at least one of the operands is
true
! Not Replaces a true with false, or a false with true.
Page 23 of 46
Example:
<script>
var x = 10;
var y = 20;
document.write("x > y: " , (x > y) , "<br>"); // false (10 is not greater than 20)
document.write("x < y: " , (x < y) , "<br>"); // true (10 is less than 20)
document.write("x >= 10: " , (x >= 10) , "<br>"); // true (10 is equal to 10)
document.write("y <= 20: " , (y <= 20) , "<br>"); // true (20 is equal to 20)
document.write("str1 === str2: " , (str1 === str2) , "<br>"); // false (different strings)
</script>
Page 24 of 46
Example 2:
<script>
var a = true;
var b = false;
var c = true;
// Explanation: Since 'a' is true but 'b' is false, the result is false.
document.write("<br><br>");
// OR operator (||)
// Explanation: Since 'a' is true, the result is true even if 'b' is false.
document.write("<br><br>");
// Explanation: The value of 'a' is true, but the NOT operator reverses it to false.
document.write("<br><br>");
// Explanation: (a && b) is false, but since 'c' is true, the OR operator makes the whole
expression
document.write("<br><br>");
</script>
Page 25 of 46
Conditional Statements:
Conditional statements allow a program to perform different actions depending on the result
of a condition.
If statement:
An if statement is used to execute a block of code only if a specified condition is true. If the
condition is false, the code inside the if block is skipped.
Example:
<body>
<h3>Enter a number:</h3>
<button onclick="checkNumber()">Check</button>
<p id="output"></p>
<script>
function checkNumber() {
number = Number(number);
</script> </body>
Page 26 of 46
If else:
If-else statement is a control flow structure that allows you to execute different blocks of code
based on certain conditions.
The if statement evaluates an expression (the condition). If the condition is true, the code
inside the if block is executed.
If the condition is false, the code inside the else block is executed.
Example:
<script> } else {
Else if:
This allows you to have multiple conditions that you set to different outcomes.
Example:
<script>
} else {
</script>
Page 27 of 46
Switch statement:
A switch statement is used to perform different actions based on different conditions. It's like
an if-else if chain, but in a more concise way, especially when checking for multiple values of a
single variable.
It can take a variable (or expression) and then check its value against a series of options.
switch (expression) {
case value1:
// code block 1;
break;
case value2:
// code block 2;
break;
...
default:
Key Points:
2. case: Each case compares the expression to a value. If it matches, the code inside that
case block is executed.
3. break: Stops the switch statement after a match is found (otherwise, it will continue
checking other cases).
Page 28 of 46
Example:
<script> break;
case 1: case 6:
break; break;
case 2: case 7:
break; break;
case 3: default:
break; }
case 4: document.write(dayName);
Ternary Operator:
The ternary operator is a special type of selection statement. It has a single comparison and
can then assign a variable a value dependent on whether this comparison is true or false.
Syntax:
Page 29 of 46
Example 1:
document.write(result);
Example 2:
document.write(result);
Loops in JavaScript
They are useful when you want to perform repetitive tasks without writing the same code
repeatedly. There are different types of loops in JavaScript: for, while, do-while, and
for...in/for...of.
1. for loop
The for loop is the most commonly used loop in JavaScript. It runs a block of code a specific
number of times, and you can define the starting point, the condition, and how to change the
value each time the loop runs.
Syntax:
Page 30 of 46
Example:
<body>
<script>
function showNumbers() {
// Loop from 1 to 5
document.write(i)
document.write(“<br>”)
</script>
</body>
2. for...in loop
The for...in loop is used to iterate over the keys (properties) of an object or elements in an
array (in terms of indexes). This loop is especially useful for looping through objects, where
you need to access both the property names (keys) and their corresponding values.
Syntax:
key: This is a variable that will hold the name of the property in the object for each iteration.
object: This is the object whose properties you want to iterate over
Page 31 of 46
Example:
<script>
var person = {
name: "Alice",
age: 25,
</script>
While loop:
The while loop in JavaScript is used to repeatedly execute a block of code as long as a specified
condition is true.
while (condition) {
condition: This is an expression that gets evaluated before each iteration of the loop. If the
condition is true, the code inside the loop runs. If it's false, the loop stops.
Code to be executed: The statements inside the loop will run as long as the condition remains
true.
Page 32 of 46
Example:
<script>
while (i <= 5) { // Condition: Loop will run as long as i is less than or equal to 5
</script>
Do/while loop:
The do...while loop is similar to the while loop, but with a key difference: the condition is
checked after the loop body is executed. This means that the code inside the loop will always
run at least once, even if the condition is false initially.
do {
// Code to be executed
} while (condition);
If the condition is true, the loop runs again. If the condition is false, the loop stops.
Page 33 of 46
Example:
<script>
do {
document.write(i + "<br>"); // Output the current value of i and add a line break
</script>
Arrays
An array in JavaScript is a special variable that can hold multiple values under one name.
Unlike regular variables that can only store a single value, an array can store multiple values of
different types (numbers, strings, objects, etc.).
Arrays in JavaScript are zero-indexed, meaning the first element is at index 0, the second
element is at index 1, and so on.
You can store any type of data in an array: numbers, strings, objects, etc.
Arrays can be accessed by their index, and you can also modify or add elements to them.
Arrays are defined using square brackets [], and elements are separated by commas.
Syntax of an Array:
Page 34 of 46
Example:
<script>
</script>
You can modify an element in an array using its index, and you can also add new elements to
the array.
Example:
<script>
fruits.push("Elderberry"); // Add a new element to the array at the end using push()
</script>
Page 35 of 46
push(): Adds an element to the end of the array.
fruits.push("Elderberry");
Timing events
In JavaScript, timing events allow you to execute functions or code after a specified amount of
time or at regular intervals. This can be useful for scenarios like animations, handling user
interactions, or scheduling tasks. There are two main methods for handling timing events in
JavaScript:
setTimeout():
Syntax:
param1, param2, ...: Optional parameters that will be passed to the function.
Page 36 of 46
Example:
<script>
function greet() {
setTimeout(greet, 2000);
</script>
setInterval():
Syntax:
interval: Time in milliseconds between each function call (1 second = 1000 milliseconds).
param1, param2, ...: Optional parameters that will be passed to the function.
Example:
script>
function repeatMessage() {
setInterval(repeatMessage, 3000);
</script>
Page 37 of 46
String manipulation
A string manipulator involves working with text(strings) to modify, extract, or analyse parts of
it. When counting letters in a string, the 1st letter is letter 0, the 2nd letter is letter 1, and so on.
Spaces and all symbols all count as letters.
Substring:
The substring (start, end) method is used to extract a part of a string between two specified
indices (start and end) and returns it as a new string. The starting index is inclusive and ending
index is exclusive (not included in the result).
Example:
<script>
document.write(result);
</script>
Substr(strat, length):
Extracts a portion of a string starting from a specified position (start) for a specified number of
characters (length). If length is omitted, it extracts until the end of the string. It also allows
negative start values, which count from the end of the string.
Example:
document.write (str.substr(-6, 6)); // scripts 6 characters strating from 6th to last index.
Page 38 of 46
replace(search, newValue):
Example:
Length:
Syntax: string.length;
Example:
document.write (str.length); // 11
Concat():
Concatenate will join string 1 and string 2 together. You can have more than two strings. It
does not modify the original strings. Using the + operator is more common.
Example:
var str1="Hello";
var str2="World";
Page 39 of 46
Changing Case:
Example:
charAt (number):
Example:
Comments
Comments are used to add explanations or annotations to the code. Comments are ignored by
the JavaScript engine, meaning they have no effect on how the code runs.
Single-line Comments begin with // and extend to the end of the line.
Page 40 of 46
Iterative methods
every method:
The every method tests whether all elements in an array pass the test implemented by the
provided function. It returns true if all elements pass the test, otherwise false.
Syntax:
});
Example:
});
document.write(areAllPositive);
some Method:
The some method checks whether at least one element in an array passes the test implemented
by the provided function. It returns true if any element passes, otherwise false.
Syntax:
});
Page 41 of 46
Example:
});
document.write(hasEven);
filter Method:
The filter method creates a new array with all elements that pass the test implemented by the
provided function. It's often used to filter out unwanted elements.
Syntax:
});
Example:
});
Page 42 of 46
foreach Method:
The forEach method is an array method that executes a provided function once for each array
element. It's an alternative to using a for loop.
Syntax:
});
Example:
fruits.forEach(function(fruit, index) {
});
Map Method:
The map method creates a new array with the results of calling a provided function on every
element in the array. Unlike forEach, map returns a new array.
Syntax:
});
Page 43 of 46
Example:
});
Trap errors
In JavaScript, errors can occur during the execution of your code due to various reasons, such
as syntax mistakes, wrong data types, or incorrect logic. JavaScript provides a way to trap and
handle these errors to prevent the program from crashing. This is achieved through try...catch
blocks and other mechanisms.
The most common way to trap and handle errors in JavaScript is by using the try...catch
statement. It allows you to attempt (or "try") executing a block of code, and if an error occurs,
it "catches" the error and executes a block of code to handle it.
Syntax:
try {
} catch (error) {
} finally {
Page 44 of 46
try Block: Contains the code that might throw an error.
catch Block: Contains code that runs if an error occurs in the try block. The error object is
passed to the catch block.
finally Block (Optional): Contains code that runs regardless of whether an error occurred or
not. It is often used for cleanup tasks
Example:
try {
let result = 10 / 0; // This will not throw an error, but a result of Infinity
} catch (error) {
} finally {
In JavaScript, you can include external scripts in your web page or application to modularize
and organize your code better. External scripts are typically stored in separate .js files and are
linked to your HTML using the <script> tag.
To include an external JavaScript file in your HTML document, you use the <script> tag with
the src (source) attribute pointing to the path of the external .js file.
Syntax:
<script src="path/to/your/script.js"></script>
Page 45 of 46
External JavaScript File (app.js)
function greet() {
alert("Hello, world!");
HTML File:
<body>
<script src="app.js">
</script>
</body>
The JavaScript file app.js is included using the <script> tag with the src attribute pointing to its
location.
The function greet() is defined in app.js, and it shows an alert when the button is clicked.
Page 46 of 46