Java Script TUTORIAL
I. Java Script(JS) Introduction
1. Introduction
JavaScript is an object-oriented, event-driven programming language widely used in web development. It
helps enhance interactivity and improve user experience
There are 3 main ways to use JS in your HTML page:
- Inline - directly on a tag
- Internal - as a block in the HTML
- External - as an external file loaded
2. Using JS in HTML page
Inline – directly on a tag
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Inline JavaScript</title>
</head>
<body>
<button onclick="alert('Welcome
to the website!')">Click
here</button>
</body>
</html>
Internal
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-
scale=1.0">
<title>Internal
JavaScript</title>
<script>
// Define a function to
display the alert
function showMessage() {
alert('Welcome to the
website!');
}
</script>
</head>
<body>
<!-- Call the function using
onclick -->
<button
onclick="showMessage()">Click
here</button>
</body>
</html>
External
external.js Index.html
function showMessage() { <!DOCTYPE html>
alert('Welcome to the website!'); <html lang="en">
} <head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-
scale=1.0">
<title>External JavaScript</title>
<script src="external.js"></script>
</head>
<body>
<!-- Call the function using onclick -->
<button onclick="showMessage()">Click
here</button>
</body>
</html>
3. Comment in JS
Single-line comment:
// This is a single-line comment
Multi-line comment:
/*
This is a multi-line comment
*/
4. Console
A real challenge when working with JS is debugging, this is because it runs instantly when you load the
page (generally) and often either works or just doesn’t - there is very little middleground due to the fact if
your code errors it tends to prevent other JS code executing
Example
<script>
// Define a function to display the alert
function showMessage() {
console.time("Execution Time");
alert('Welcome to the website!');
console.log("Hello, world!");
console.log(123);
console.log({ name: "John", age: 30 });
console.timeEnd("Execution Time");
}
</script>
console.log() - Print information to the console
console.time() & console.timeEnd() - Measure execution time
5. Variable
A variable is a memory space used to store data. In JavaScript, there are three ways to declare variables:
Automatically, `var`, `let`, `const`.
Example:
a = 5;
var x = 5; // Declare variable x in function scope or global scope
let y = 10; // Declare variable y in block-level scope or global scope
const z = 15; // Declare constant z
The var keyword was used in all JavaScript code from 1995 to 2015.
The let and const keywords were added to JavaScript in 2015.
The var keyword should only be used in code written for older browsers.
When to Use var, let, or const?
1. Always declare variables
2. Always use const if the value should not be changed
3. Always use const if the type should not be changed (Arrays and Objects)
4. Only use let if you can't use const
5. Only use var if you MUST support old browsers .
if (true) {
var x = 10; // function or global scope
let y = 20; // block scope
}
console.log(x); // 10 (var has function scope, so it is accessible outside
the block)
console.log(y); // Uncaught ReferenceError: y is not defined (let has block
scope)
6. Dialog/log
In JavaScript, dialog boxes are small windows that the browser displays to the user to provide information or
ask for interaction. Dialog boxes are commonly used to show notifications, warnings, or request user input.
JavaScript provides 3 basic types of dialog boxes:
Alert Dialog Box (alert())
The alert dialog box is used to display a message to the user with an "OK" button to dismiss the dialog.
Syntax: alert("This is an alert box!");
Confirm Dialog Box (confirm()) s
The confirm dialog box asks the user to confirm an action. It displays a message with two buttons: "OK" (or
"Yes") and "Cancel" (or "No"). The confirm() method returns true if the user clicks "OK" and false if they
click "Cancel".
Syntax: let userChoice = confirm("Do you want to continue?");
userChoice will store true or false.
Promt
The prompt dialog box asks the user to input some data. It contains a text input field and two buttons: "OK"
and "Cancel". The prompt() method returns the value entered by the user, or null if they click "Cancel".
Syntax: let userInput = prompt("Please enter your name:", "Default value");
If the user enters a value and clicks "OK", that value will be returned. If the user clicks "Cancel", null will be
returned
Log function
The console.log() method is used to log information to the browser’s console. It is an essential tool for
checking, debugging, or outputting values during development
Example: console.log("This is a message");
Example 2:
let name = "Alice";
console.log("Hello, " + name);
7. Functions
A function is a block of code that is designed to perform a particular task, usually returning the outcome of
that task to the caller.
When we want to use a function we “call” it, or execute/invoke it. This is to mean we tell the code to run the
code within the function.
A function can return or not return data
Method 1: Using `function`:
function greet(name) {
return `Hello, ${name}!`;
console.log(greet('Lan'));
Method 2: Using arrow functions:
const greet = (name) => `Hello, ${name}!`;
console.log(greet('Lan'));
8. Interact with HTML page
JS can interact with HTML element through attribute, ID, class, tag name a bit like CSS. This mean that you
should give the tags that you want to interact with an id, class… so that you can identify them later in js.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JavaScript Interaction Example with Forms</title>
<style>
.highlight {
color: red;
}
</style>
</head>
<body>
<h1 id="header">Welcome to My Page</h1>
<p class="text">This is the first paragraph.</p>
<p class="text">This is the second paragraph.</p>
<img id="myImage" src="dog.jpg" alt="Placeholder Image">
<br>
<input type="text" id="textbox" value="Enter some text">
<br>
<select id="selectBox">
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
<option value="option3">Option 3</option>
</select>
<br>
<input type="checkbox" id="checkbox" checked>
<br>
<button onclick="changeHeader()">Change Header Text</button>
<button id="changeTextBtn">Change Paragraph Text</button>
<button onclick="highlightText()">Highlight Text</button>
<br>
<button onclick="changeImage()">Change Image</button>
<br>
<button onclick="getTextboxValue()">Get Textbox Value</button>
<button onclick="setTextboxValue()">Set Textbox Value</button>
<br>
<button onclick="getSelectValue()">Get Selected Option</button>
<button onclick="setSelectValue()">Set Selected Option</button>
<br>
<button onclick="getCheckboxValue()">Get Checkbox Value</button>
<button onclick="checkCheckbox()">Check the Checkbox</button>
<button onclick="uncheckCheckbox()">Uncheck the Checkbox</button>
<script>
// 1. Change the header text using ID
function changeHeader() {
document.getElementById("header").innerText = "Hello, World!";
}
// 2. Change paragraph text using Class
function changeParagraphText() {
const paragraphs = document.getElementsByClassName("text");
for (let i = 0; i < paragraphs.length; i++) {
paragraphs[i].innerText = "This paragraph has been changed!";
}
}
// 3. Add CSS class to highlight text using Class
function highlightText() {
const paragraphs = document.getElementsByClassName("text");
for (let i = 0; i < paragraphs.length; i++) {
paragraphs[i].classList.add("highlight");
}
}
// 4. Change image attributes (src and alt) using Attribute
function changeImage() {
const image = document.getElementById("myImage");
image.setAttribute("src", "cat.jpg");
image.setAttribute("alt", "New Image");
}
// 5. Get value from textbox (input)
function getTextboxValue() {
const textboxValue = document.getElementById("textbox").value;
alert("Textbox value: " + textboxValue);
}
// 6. Set value for textbox
function setTextboxValue() {
document.getElementById("textbox").value = "New value set!";
}
// 7. Get selected value from select box (dropdown)
function getSelectValue() {
const selectedOption = document.getElementById("selectBox").value;
alert("Selected option: " + selectedOption);
}
// 8. Set selected value for select box
function setSelectValue() {
document.getElementById("selectBox").value = "option2"; // Setting to
Option 2
}
// 9. Get checkbox value (checked or unchecked)
function getCheckboxValue() {
const checkboxStatus = document.getElementById("checkbox").checked;
alert("Checkbox is checked: " + checkboxStatus);
}
// 10. Check the checkbox
function checkCheckbox() {
document.getElementById("checkbox").checked = true; // Checking the
checkbox
}
// 11. Uncheck the checkbox
function uncheckCheckbox() {
document.getElementById("checkbox").checked = false; // Unchecking the
checkbox
}
// Assign the onclick event to the Change Paragraph Text button using its
ID
document.getElementById("changeTextBtn").onclick = changeParagraphText;
</script>
</body>
</html>
Method to get html element
Method Return Type Description Example Usage
Returns the
DOM element
const element =
Object (Element) with the
getElementById() document.getElementById("myElement");
or null matching id (or console.log(element);
null if not
found)
Returns an
HTMLCollecti const elements =
getElementsByClassName() HTMLCollection on of elements document.getElementsByClassName("myClass");
with the console.log(elements[0]);
matching class
Returns an
HTMLCollecti
on of elements const divs = document.getElementsByTagName("div");
getElementsByTagName() HTMLCollection
with the console.log(divs[0]);
matching tag
name
Returns the
first element
Object (Element) that matches a const element = document.querySelector(".myClass");
querySelector()
or null CSS selector console.log(element);
(or null if not
found)
Returns a
NodeList of all const elements =
document.querySelectorAll(".myClass");
elements
querySelectorAll() NodeList console.log(elements.length);
matching the
CSS selector cont ptag=document.querySelectorAll("p");
Or tag
Properties to get set value for html element
Property Description Get Example Set Example
Gets or sets the
visible text
innerText const text = element.innerText; element.innerText = "New Text!";
content inside an
element
Gets or sets the
HTML content
element.innerHTML =
innerHTML (including tags) const htmlContent = element.innerHTML;
"<strong>New Content</strong>";
inside an
element
Gets or sets the
value of form
value
elements like const value = inputElement.value; inputElement.value = "New value";
<input>,
<textarea>,
<select>
Gets or sets the
checked state of
checked const isChecked = checkboxElement.checked; checkboxElement.checked = true;
checkboxes or
radio buttons
Adds, removes,
or toggles CSS
classList element.classList.contains("myClass"); element.classList.add("newClass");
classes of an
element
Gets or sets
element.style.backgroundColor =
style inline CSS styles const bgColor = element.style.backgroundColor;
"red";
for an element
<ol id="myList">
<li>task 1</li>
<li>task 2</li>
<li>task 3</li>
Get the last child
element (HTML </ol>
lastElementChild element) of a let parentElement =
specified parent document.getElementById('myList
element ');
let lastChild =
parentElement.lastElementChild;
the last emelent is task 3
firstElementChild Get the first <ol id="myList">
child element <li>task 1</li>
(HTML element) <li>task 2</li>
of a specified <li>task 3</li>
</ol>
let parentElement =
document.getElementById('myList
parent element ');
let firstChild = parentElement.
firstElementChild;
the first emelent is task 1
Return all the
element nodes
(HTML
children let children = parentElement.children;
elements) that
are children of
the given parent
Event attribute
Property Description Get Example
onclick is an event attribute used to Html
assign a function or a block of JavaScript <button onclick="alert('Button clicked!')">Click me</button>
code that will be executed when a user Javascript
clicks on an HTML element (such as a <button id="myButton">Click me</button>
onclick
button, link, image, etc.). The onclick <script>
event can be used with any HTML document.getElementById("myButton").onclick = function()
element and allows you to handle user { alert("Button clicked!"); };
interactions on the webpage. </script>
Triggered when the user double-clicks on
ondblclick
an element
Triggered when the user presses a key on
onkeydown
the keyboard
Triggered when the user releases a key
onkeyup
on the keyboard
Triggered when the user presses a key
onkeypress that produces a character (e.g., letters,
numbers).
<form onsubmit="alert('Form submitted!');
return false;">
onsubmit Triggered when the user submits a form <input type="text">
<input type="submit" value="Submit">
</form>
Method to create html element
Method Description Get Example
Creates a new HTML
document.createElement(tagName) element with the let div = document.createElement('div');
specified tagName.
document.createTextNode(text) Creates a text node let text = document.createTextNode('Hello, World!');
with the content
text
Appends a child
element (child) to
parentNode.appendChild(child) parentNode.appendChild(newDiv);
a parent element
(parentNode).
Inserts newNode
parentNode.insertBefore(newNode, before parentNode.insertBefore(newElement,
referenceNode) referenceNode in referenceElement);
the parent element.
Removes a child
element (child)
element.removeChild(child) parentElement.removeChild(childElement);
from a parent
element (element).
Example of get element, create new element, add, remove element
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>List Add and Remove</title>
<style>
button {
margin: 10px;
}
</style>
</head>
<body>
<h2>List</h2>
<ol id="myList"></ol>
<button id="addButton">Add</button>
<button id="removeButton">Remove</button>
<script>
// Get the elements from the DOM
const addButton =
document.getElementById("addButton");
const removeButton =
document.getElementById("removeButton");
const myList =
document.getElementById("myList");
// Function to add an item to the list
addButton.onclick = function() {
const newItem =
document.createElement("li"); // Create <li> element
newItem.innerText = "Item " +
(myList.children.length + 1); // Set item text
myList.appendChild(newItem); // Add item
to <ol>
};
// Function to remove an item from the list
removeButton.onclick = function() {
if (myList.children.length > 0) {
myList.removeChild(myList.lastElementChild); // Remove
the last item
}
};
</script>
</body>
</html>
Exercise 1: Fix the code above that allow the user to remove item when they click on an item in the list
Hint assign onClick event with a function that use myList to removeChild element
Exercise 2: Write the example assignment again but use table instead of ol.
Exercise 3: Do the exercise 2 again but use innerHTML for row;
9. Data conversion
Converting to String (String Conversion)
Convert a value to a string.
Methods:
String(value): Explicit conversion.
toString(): A method available on most objects (except null and undefined).
Example
let num = 123;
console.log(String(num)); // "123" (explicit)
console.log(num.toString()); // "123" (method)
console.log(num + ""); // "123" (implicit)
let bool = true;
console.log(String(bool)); // "true"
console.log(bool + ""); // "true"
Converting to Number (Number Conversion)
Convert a value to a number.
Methods:
Number(value): Explicit conversion.
Unary plus (+value): Implicit conversion.
parseInt() or parseFloat(): Converts strings to integers or floating-point numbers.
Example:
let str = "123";
console.log(Number(str)); // 123 (explicit)
console.log(+str); // 123 (implicit)
console.log(parseInt(str)); // 123
console.log(parseFloat("123.45")); // 123.45
let bool = false;
console.log(Number(bool)); // 0
console.log(+bool); // 0
10. Control structure
Conditional Statements (if/else):
let age = 20;
if (age >= 18) {
console.log('You are an adult.');
} else {
console.log('You are not an adult.');
Difference between == and ====
Aspect == (Equality) === (Strict Equality)
Performs type conversion before
Type Conversion No type conversion
comparison
Comparison Logic Compares values after coercion Compares values and types
Example (5 vs '5') 5 == '5' → true 5 === '5' → false
0 == false → true (false coerces to 0 === false → false (different
Example (0 vs false)
0) types: number vs boolean)
null == undefined → true (special null === undefined → false
Special Cases
loose equality) (strict type comparison)
Difference between != and !==
Aspect != (Inequality) !== (Strict Inequality)
Performs type conversion before No type conversion, compares
Type Conversion
comparison values as-is
Comparison Logic Compares values after coercion Compares values and their types
5 != '5' → false (values coerced to 5 !== '5' → true (different
Example (5 vs '5')
same type) types: number vs string)
null != undefined → false (special null !== undefined → true
Special Cases
case) (different types)
Loops:
- for loop:
for (let i = 0; i < 5; i++) {
console.log(i);
- while loop:
let i = 0;
while (i < 5) {
console.log(i);
i++;
- do-while loop:
let i = 0;
do {
console.log(i);
i++;
} while (i < 5);
11. Libraries
Math Library
The Math object provides mathematical constants and functions.
Common Methods:
Math.random(): Generates a random number between 0 (inclusive) and 1 (exclusive).
Math.round(): Rounds a number to the nearest integer.
Math.floor(): Rounds a number down to the nearest integer.
Math.ceil(): Rounds a number up to the nearest integer.
Math.max() / Math.min(): Returns the maximum or minimum value from a list of numbers.
Math.sqrt(): Returns the square root of a number.
Math.pow(): Raises a number to the power of another number.
Example:
console.log(Math.random()); // Random number between 0 and 1
console.log(Math.round(4.7)); // 5
console.log(Math.floor(4.7)); // 4
console.log(Math.ceil(4.7)); // 5
console.log(Math.max(10, 20, 30)); // 30
console.log(Math.sqrt(16)); // 4
console.log(Math.pow(2, 3)); // 8
Date Library
The Date object is used to work with dates and times.
Common Methods:
new Date(): Creates a new Date object representing the current date and time.
getFullYear(): Gets the year of a date.
getMonth(): Gets the month (0-based).
getDate(): Gets the day of the month.
getDay(): Gets the day of the week (0 = Sunday, 6 = Saturday).
getHours(), getMinutes(), getSeconds(): Gets the respective time components.
Example
let now = new Date();
console.log(now); // Current date and time
console.log(now.getFullYear()); // Current year
console.log(now.getMonth() + 1); // Current month (add 1 because it's 0-
based)
console.log(now.getDate()); // Day of the month
console.log(now.getHours() + ":" + now.getMinutes()); // Current time
String Library
The String object has methods to manipulate text.
Common Methods:
charAt(): Returns the character at a specific index.
substring(): Extracts a part of the string.
toUpperCase() / toLowerCase(): Converts a string to uppercase or lowercase.
split(): Splits a string into an array.
trim(): Removes whitespace from both ends of a string.
includes(): Checks if a substring exists within a string.
Example
let text = " Hello, World! ";
console.log(text.trim()); // "Hello, World!"
console.log(text.toUpperCase()); // " HELLO, WORLD! "
console.log(text.includes("World")); // true
console.log(text.substring(2, 7)); // "Hello"
console.log(text.split(",")); // [" Hello", " World! "]
Array Library
The Array object provides methods for array manipulation.
Common Methods:
push(): Adds an element to the end of the array.
pop(): Removes the last element from the array.
shift() / unshift(): Removes or adds elements to the start of the array.
map(): Applies a function to each element and returns a new array.
filter(): Returns a new array with elements that pass a test.
reduce(): Reduces the array to a single value by applying a function.
forEach(): Executes a function for each array element.
.Length: return the number of element
Example
let numbers = [1, 2, 3, 4, 5];
console.log(numbers.map(x => x * 2)); // [2, 4, 6, 8, 10]
console.log(numbers.filter(x => x > 2)); // [3, 4, 5]
console.log(numbers.reduce((sum, x) => sum + x, 0)); // 15
numbers.push(6); // Adds 6 to the end
console.log(numbers); // [1, 2, 3, 4, 5, 6]
numbers.pop(); // Removes last element
console.log(numbers); // [1, 2, 3, 4, 5]
JSON (JavaScript Object Notation)
The JSON object is used for parsing and stringifying JSON data.
Common Methods:
JSON.stringify(): Converts a JavaScript object to a JSON string.
JSON.parse(): Converts a JSON string to a JavaScript object.
Example
let person = { name: "Alice", age: 25 };
let jsonString = JSON.stringify(person);
console.log(jsonString); // '{"name":"Alice","age":25}'
let jsonObject = JSON.parse(jsonString);
console.log(jsonObject.name); // "Alice"
12. Object
JavaScript Objects are a basic data type in JavaScript used to store key-value pairs. Each key-value pair in an
object is called a property of that object
Basic structure
let person = {
name: "John",
age: 30,
city: "New York"
};
Where:
person is the name of the object.
name, age, city are the keys.
"John", 30, "New York" are the corresponding values
Accessing and Changing Values in an Object
- Accessing Values
You can access the value of a property using either dot (.) notation or bracket ([]) notation.
// Using dot notation
console.log(person.name); // Output: John
// Using bracket notation
console.log(person["age"]); // Output: 30
- Changing Values
To change the value of a property, you can assign a new value to it.
person.age = 35; // Change the age of person
console.log(person.age); // Output: 35
person["city"] = "Los Angeles"; // Change the city
console.log(person.city); // Output: Los Angeles
Methods in Objects
Methods are functions that can be defined inside an object. For example:
let person = {
name: "John",
greet: function() {
console.log("Hello, " + this.name);
};
person.greet(); // Output: Hello, John
Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-
scale=1.0">
<title>User Information
Management</title>
</head>
<body>
<h1>User Information Management</h1>
<form id="userForm">
<label for="firstName">First
Name:</label>
<input type="text" id="firstName"
placeholder="Enter first name">
<br><br>
<label for="lastName">Last
Name:</label>
<input type="text" id="lastName"
placeholder="Enter last name">
<br><br>
<button type="button"
onclick="displayUserInfo()">Display</butt
on>
</form>
<h2>User Information:</h2>
<p id="userInfo"></p>
<script>
// Define a user object to store user
information
let user = {
firstName: '',
lastName: ''
};
// Function to get data from the form
and update the object
function displayUserInfo() {
// Get data from the input fields
const firstName =
document.getElementById('firstName').valu
e;
const lastName =
document.getElementById('lastName').value
;
// Update the user object
user.firstName = firstName;
user.lastName = lastName;
// Display user information on the
interface
const userInfo =
document.getElementById('userInfo');
userInfo.innerHTML = `First Name: $
{user.firstName} <br> Last Name: $
{user.lastName}`;
}
</script>
</body>
</html>
Object and array
- Definition
An array is a data type used to store a list of values, where each value is associated with an index. The
elements in an array can be of any data type.
Example
// An array with elements of different data types
let fruits = ["Apple", "Banana", "Orange"];
// Accessing the value of elements in the array
console.log(fruits[0]); // Output: Apple
console.log(fruits[2]); // Output: Orange
// Adding an element to the array
fruits.push("Grapes"); // Adds "Grapes" to the end of the array
console.log(fruits); // Output: ["Apple", "Banana", "Orange", "Grapes"]
- Store object in array
let students = [
{ name: "John", age: 20, subjects: ["Math", "Physics"] },
{ name: "Alice", age: 22, subjects: ["Biology", "Chemistry"] },
{ name: "Bob", age: 21, subjects: ["History", "Literature"] }
];
// Accessing the name of the first student
console.log(students[0].name); // Output: John
// Accessing the first subject of the second student
console.log(students[1].subjects[0]); // Output: Biology
Iteration
- Using traditional for loop
const students = [
{ name: "John", age: 20 },
{ name: "Alice", age: 22 },
{ name: "Bob", age: 21 }
];
for (let i = 0; i < students.length; i++) {
console.log(`${students[i].name} is ${students[i].age} years old.`);
Using forEach
const students = [
{ name: "John", age: 20 },
{ name: "Alice", age: 22 },
{ name: "Bob", age: 21 }
];
students.forEach(student => {
console.log(`${student.name} is ${student.age} years old.`);
});
s