JavaScript Notes
JavaScript Notes
A “Hello, World!” program is the simplest way to get started with any
programming language. Here’s how you can write one using JavaScript.
<html>
<head></head>
<body>
<h1>Check the console for the message!</h1>
<script>
// This is our first JavaScript program
console.log("Hello, World from console..!");
alert("Hello, World from alert..!");
</script>
</body>
</html>
In this example
We can also print the “Hello World” program directly into the console
terminal without embedded it into HTML. Create an index.js file and add the
code to it.
In this example
Applications of JavaScript
JavaScript Syntax
JavaScript syntax refers to the rules and conventions dictating how code is
structured and arranged within the JavaScript programming language. This
includes statements, expressions, variables, functions, operators and control
flow constructs.
In coding, “syntax” refers to the set of rules that defines the structure and
format of the code in a programming language. It dictates how code should
be written so that it can be correctly interpreted and executed by the
compiler or interpreter.
JavaScript code is embedded in HTML using the <script> tag. The script can
be added using several methods i.e.
1. Inline JavaScript
Writing JavaScript code directly inside the HTML element using the onclick,
onmouseover, or other event handler attributes. E.g.
<html>
<head></head>
<body>
<h2> Adding JavaScript in HTML Document </h2>
<button onclick="alert('JavaScript Button Clicked..!')"> Click Here
</button>
</body>
</html>
You can write JavaScript code inside the <script> tag within the HTML file.
This is known as internal JavaScript and is commonly placed inside the
<head> or <body> section of the HTML document.
<html>
<head>
<script>
function myFun() {
document.getElementById("demo")
.innerHTML = "This content is from JavaScript Code Inside
head Tag..!";
}
</script>
</head>
<body>
<h2>Add JavaScript Code inside Head Section </h2>
<h3 id="demo" style="color:green;"> To demostrate JavaScript
Code Inside head Tag </h3>
<button type="button" onclick="myFun()"> Click Here </button>
</body>
</html>
<html>
<head></head>
<body>
<h2> Add JavaScript Code inside Body Section </h2>
<h3 id="demo" style="color:green;"> To demostrate JavaScript Code
Inside body Tag </h3>
<button type="button" onclick="myFun()"> Click Here </button>
<script>
function myFun() {
document.getElementById("demo")
.innerHTML = " This content is from JavaScript Code Inside body
Tag..!";
}
</script>
</body>
</html>
For larger projects or when reusing scripts across multiple HTML files, you
can place your JavaScript code in an external .js file. This file is then linked to
your HTML document using the src attribute within a <script> tag.
HTML:
<html>
<head>
<script src="script.js"></script>
</head>
<body>
<h2> External JavaScript </h2>
<h3 id="demo" style="color:green;"> To demonstrate External
JavaScript </h3>
<button type="button" onclick="myFun()"> Click Here </button>
</body>
</html>
JavaScript:
/* Filename: script.js*/
function myFun () {
document.getElementById('demo')
Faster Page Load Times: Cached external JavaScript files don’t need
to be reloaded every time the page is visited, which can speed up
loading times.
1. async Attribute
This attribute loads the script asynchronously, i.e. the script will be
downloaded and executed as soon as it is available, without blocking the
page.
<script src="script.js" async></script>
2. defer Attribute
This attribute delays the execution of the script until the entire HTML
document has been parsed. This is particularly useful for scripts that
manipulate the DOM.
<script src="script.js" defer></script>
Referencing External JavaScript Files
There are three ways to reference an external script in JavaScript:
By using a full URL: src = "https://www.kcau.ac.ke/js/script.js"
By using a file path: src = "/js/script.js"
Without using any path: src = "script.js"
JavaScript Output:
1. Using innerHTML
<!DOCTYPE html>
<html>
<body>
<h2>Inner HTML output</h2>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = 5 + 6;
</script>
</body>
</html>
2. Using document.write()
<!DOCTYPE html>
<html>
<body>
<h2>Using Document.write</h2>
<script> document.write(5 + 6); </script>
</body>
</html>
Note: Using document.write() after an HTML document is loaded, will delete
all existing HTML. Thus document.write() method should only be used for
testing. E.g.
<!DOCTYPE html>
<html>
<body>
<h2>Using Document.write - deletes html </h2>
<p>Other html data that will be deleted also </p>
<button type="button" onclick="document.write(5 + 6)">Click Here
</button>
</body>
</html>
3. Using window.alert()
<!DOCTYPE html>
<html>
<body>
<h2>Using windows alert </h2>
<script>
window.alert(5 + 6);
//alert(5 + 6);
</script>
</body>
</html>
You can skip the window keyword as shown under the commented line.
The window object is the global scope object. This means that variables,
properties, and methods by default belong to the window object. This
also means that specifying the window keyword is optional.
4. Using console.log()
For debugging purposes, you can call the console.log() method in the
browser to display data.
<!DOCTYPE html>
<html>
<body>
</body>
</html>
JavaScript Print
JavaScript does not have any print object or print methods; thus you cannot
access output devices from JavaScript.
The only exception is that you can call the window.print() method in the
browser to print the content of the current window.
<!DOCTYPE html>
<html>
<body>
<h2>Using windows print function: </h2>
<p>This will print the <b> current page </b> to either device, pdf
format etc.</p>
<button onclick="window.print()">Print this page</button>
</body>
</html>
JavaScript Statements/code
JavaScript statements are programming instructions that a computer
executes. They are composed of:
Values
Operators
Expressions
Keywords
Comments
This statement tells the browser to write a given data/ statement inside an
HTML element id. E.g.
document.getElementById("demo").innerHTML = "Internet application
Programming.";
The statements are executed, one by one, in the same order as they are
written.
Keyword Description
var Declares a variable
let Declares a block variable
const Declares a block constant
if Marks a block of statements to be executed on a condition
switch Marks a block of statements to be executed in different cases
for Marks a block of statements to be executed in a loop
function Declares a function
return Exits a function
try Implements error handling to a block of statements
Note: Reserved words cannot be used as names for variables.
Giving examples, discuss various types of JavaScript statements?
JavaScript Events:
<html>
<script>
function myFun() {
document.getElementById(
"iap").innerHTML = "Click event triggered, for Internet
Application Programming";
}
</script>
<body>
<button onclick="myFun()">Click me </button>
<p id="iap"></p>
</body>
</html>
The onclick attribute in the <button> calls the myFun() function
when clicked.
Initially, the <p> is empty, and its content changes dynamically on the
button click.
Event Types:
Event Description
Attribute
onclick Triggered when an element is clicked.
onmouseover Fired when the mouse pointer moves over an
element.
onmouseout Occurs when the mouse pointer leaves an
element.
onkeydown Fired when a key is pressed down.
onkeyup Fired when a key is released.
onchange Triggered when the value of an input element
changes.
onload Occurs when a page has finished loading.
onsubmit Fired when a form is submitted.
onfocus Occurs when an element gets focus.
onblur Fired when an element loses focus.
<html>
<body>
<h2> Inline HTML Handlers </h2>
<button onclick="alert('Button clicked!')">Click Me</button>
</body>
</html>
2. DOM Property Handlers
3. addEventListener() (Preferred)
btn.addEventListener("click", () => {
alert("Button clicked using addEventListener!");
});
Practical Applications
1. Form Validation
<html>
<body>
<h2>Form Validation</h2>
<form id="formval">
<input type="text" placeholder="Enter some values"
id="formInput" />
<button type="submit">Submit</button>
</form>
<script>
document.querySelector("#formval").addEventListener("submit",
(e) => {
let input = document.querySelector("#formInput");
if (!input.value) {
e.preventDefault();
alert("Input cannot be empty");
}
else{
alert("Something inserted into database.");
}
});
</script>
</body>
</html>
JavaScript Variables
JavaScript Variables can be declared in 4 ways:
Automatically
Using var
Using let
Using const
var a = 10 // Old style
let b = 20; // Prferred for non-const
const c = 30; // Preferred for const (cannot be changed)
The var keyword was used in all JavaScript code from 1995 to 2015.
The var keyword should only be used in code written for older browsers.
JavaScript Identifiers
The general rules for constructing names for variables (unique identifiers)
are:
Variable names must begin with a letter, underscore (_), or dollar sign
($).
Names are case sensitive (y and Y are different variables).
var carName;
let carName;
Variable initialization
carName = "Nissan";
Program Example
<p id="demo"></p>
<script>
let carName = "Nissan";
document.getElementById("demo").innerHTML = carName;
</script>
You can declare many variables in one statement by starting the statement
with let and separate the variables by comma:
Importance
Variables can be declared with different scopes, affecting where and how
they can be accessed.
Global Variables
They are declared outside of any function or block scope.
They are accessible from anywhere within the script, including inside
functions and blocks. Variables declared without the var, let,
or const keywords inside a function automatically become global variables.
However, variables declared with var, let, or const inside a function are local
to that function unless explicitly marked as global using window (in browser
environments) or global (in Node.js).
Example:
<!DOCTYPE html>
<html>
<head><title>Global Variables</title></head>
<body>
<script>
let petName = 'Jimmy' // Global variable
myFunction()
function myFunction() {
fruit = 'apple'; // Considered global
console.log('My pet name is ' + petName + ' - from global')
}
console.log('My pet name is ' + petName +'.' + ' Fruit name is ' +
fruit + ' - Considered global')
</script>
</body>
</html>
Local Variables
Local variables are defined within functions in JavaScript.
They are confined to the scope of the function that defines them and cannot
be accessed from outside.
Attempting to access local variables outside their defining function results in
an error.
Example:
<!DOCTYPE html>
<html>
<head><title>Local Variables</title></head>
<body>
<script>
myfunction();
anotherFunc();
let petName;
function myfunction() {
let petName = "Simba"; // local variable
console.log(petName);
}
function anotherFunc() {
let petName = "Jimmy"; // local variable
console.log(petName);
}
console.log(petName);
</script>
</body>
</html>
More Examples:
<!DOCTYPE html>
<html>
<body>
<h1>Calculate Area and Circumference</h1>
<p id="area1"></p>
<p id="cir"></p>
<script>
// Capture the radius from the user using prompt()
let radius = parseFloat(prompt("Enter the radius of the circle:"));
<!DOCTYPE html>
<html>
<body>
<h1>Add Two Numbers Entered by the User</h1>
<p>JavaScript program to add two numbers captured from user
keyboard.</p>
<p id="add"></p>
<script>
// store input numbers
const num1 = parseInt(prompt('Enter the first number '));
const num2 = parseInt(prompt('Enter the second number '));
//add two numbers
const sum = num1 + num2;
<!DOCTYPE html>
<html>
<head><title>Area of triangle</title></head>
<body>
<p id="area1"></p>
<script>
const baseValue = prompt('Enter the base of a triangle: ');
const heightValue = prompt('Enter the height of a triangle:
');
// calculate the area
const areaValue = (baseValue * heightValue) / 2;
document.getElementById("area1").innerHTML = "The area
of the triangle is: "+ areaValue;
</body>
</html>
JavaScript Operators
1. Arithmetic Operators
Used to assign values to variables. They can also perform operations like
addition or multiplication before assigning the value.
=== compares values without type coercion, ensuring both the value and
type must match exactly.
Comparison operators are mainly used to perform the logical operations that
determine the equality or difference between the values.
Example:
console.log(res);
Example:
Output: 3
They are used to compare its operands and determine the relationship
between them. They return a Boolean value (true or false) based on the
comparison result.
They are:
Output:
true
false
Output:
true
true
false
false
In JavaScript,
1. Concatenate Operator
This combines strings using the ‘+’ operator and creates a new string.
let str1 = "BIT 04204";
let str2 = " Internet Application Programming";
let result = (str1 + str2);
console.log(result);
Output:
BIT 04204 Internet Application Programming
Output:
BIT 04204 Internet Application Programming
Control Structures
In JavaScript we have the following conditional statements:
Use if to specify a block of code to be executed, if a specified condition
is true
Use else to specify a block of code to be executed, if the same
condition is false
Use else if to specify a new condition to test, if the first condition is
false
Use switch to specify many alternative blocks of code to be executed
The if Statement
Syntax:
if (condition) {
// block of code to be executed if the condition is true
}
Example:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript if</h2>
<p id="age"> if condtion..!</p>
<script>
let age1 = parseInt(18);
if (age1<= 18) {
document.getElementById("age").innerHTML = "You are a Young
person. !";
}
</script>
</body>
</html>
if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}
Example:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript if-else</h2>
<p id="age"> if else structure..! </p>
<script>
let age1 = parseInt(prompt("Enter your age: "));
if (age1<= 18) {
document.getElementById("age").innerHTML = "You are a Young
person. !";
}
else {
document.getElementById("age").innerHTML = "You are an Adult. !";
}
</script>
</body>
</html>
Use the else if statement to specify a new condition if the first condition is
false.
Syntax:
if (condition1) {
// block of code
}
else if (condition2) {
// block of code
else if (n) {
// block of code
}
else {
// block of code – like default
}
Example:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript if</h2>
<p id="marks">if else if - grading system..!</p>
<script>
let avg_marks = parseInt(prompt("Enter your avarage marks: "));
Use the switch statement to select one of many code blocks to be executed.
Syntax:
switch(expression) {
case 1:
// statement(s)
break;
case 2:
// statement(s)
break;
…..
default:
// statement(s)
}
Example:
<!DOCTYPE html>
<html>
<body>
<p id="day"></p>
<script>
//let day1 = parseInt(prompt("Enter 0 - 6, to see the day: "));
let day;
switch (new Date().getDay()){
//switch (day1) {
case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
case 3:
day = "Wednesday";
break;
case 4:
day = "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
break;
default:
day = "Invalid day of the week. Please put 0 - 6";
}
document.getElementById("day").innerHTML = "Today is " + day;
</script>
</body>
</html>
JavaScript Loops
Loops are used to reduce repetitive tasks by repeatedly executing a block of
code as long as a specified condition is true. This makes code more concise
and efficient.
Types of Loops
JavaScript supports different kinds of loops:
for - loops through a block of code a number of times
for/in - loops through the properties of an object
for/of - loops through the values of an iterable object
while - loops through a block of code while a specified condition is true
do/while - also loops through a block of code while a specified
condition is true
Example:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript for loop</h2>
<script>
//let i = 5;
for (let i = 1; i <= 5; i++) {
console.log("Count:", i);
}
</script>
</body>
</html>
Output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
In this example
Initializes the counter variable (let i = 1).
Tests the condition (i <= 3); runs while true.
Executes the loop body and increments the counter (i++).
Example:
<!DOCTYPE html>
<html>
<body>
Example Explained
The for in loop iterates over a person object
Each iteration returns a key (x)
The key is used to access the value of the key
The value of the key is person[x]
Syntax:
for (variable of iterable) {
// code block to be executed
}
variable - For every iteration the value of the next property is assigned to
the variable. Variable can be declared with const, let, or var.
iterable - An object that has iterable properties.
Example:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript For Of Loop</h2>
<p id="car"></p>
<script>
const cars = ["BMW", "Volvo", "Nissan","VW"];
let text = "";
for (let x of cars) {
text += x + "<br>";
}
document.getElementById("car").innerHTML = text;
</script>
</body>
</html>
The while loop executes as long as the condition is true. It can be thought of
as a repeating if statement.
Syntax:
while (condition) {
// Code to execute
}
Example:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript while loop</h2>
<script>
let count = 1;
while (count <= 5) {
console.log(count);
count++;
}
</script>
</body>
</html>
Output:
1
2
3
4
5
The do-while loop is similar to while loop except it executes the code block at
least once before checking the condition.
Syntax:
do {
// Code to execute
} while (condition);
Example:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript do while loop</h2>
<script>
let test = 1;
do {
console.log(test);
test++;
} while(test<=5)
</script>
</body>
</html>
Output:
1
2
3
4
5
Nested loops.
A nested loop is a loop within another loop.
Example 1: Right-Angled Triangle Pattern
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
<body> <body>
<h2>Pattern using for loop <h2>Right-Angled Triangle using while
</h2> loop </h2>
<script> <script>
let rows = let rows = parseInt(prompt("Enter the
parseInt(prompt("Enter the number of rows:"));
number of rows:")); let i = 1;
let pattern = ""; let pattern = "";
<h2>Number Pyramid using for loop <h2>Pyramid Pattern using while Loop
</h2> </h2>
<script> <script>
let rows = parseInt(prompt("Enter the let rows = parseInt(prompt("Enter the
number of rows:")); number of rows:"));
let pattern = ""; let i = 1;
let pattern = "";
for (let i = 1; i <= rows; i++) {
for (let j = 1; j <= rows - i; j++) { while (i <= rows) {
pattern += " "; let spaces = 1;
} while (spaces <= rows - i) {
for (let k = 1; k <= i; k++) { pattern += " ";
pattern += k + " "; spaces++;
} }
pattern += "\n"; let stars = 1;
} while (stars <= 2 * i - 1) {
pattern += "*";
console.log(pattern); stars++;
alert(pattern); }
pattern += "\n";
</script> i++;
</body> }
</html> console.log(pattern);
alert(pattern);
</script>
</body>
</html>
console.log(pattern);
alert(pattern);
</script>
</body>
</html>
JavaScript Function
These are reusable blocks of code designed to perform specific tasks. They
allow you to organize, reuse, and modularize code. It can take inputs,
perform actions, and return outputs.
Function Declarations
A Function Declaration (also known as a Function Statement) is a way
to define a function in programming. It is a statement that creates a function
with a specified name and body, allowing it to be called anywhere in the
code.
Syntax:
function functionName(parameters) {
// function body
return someValue; // (optional)
}
Example:
function sum(x, y) {
return x + y;
}
console.log(sum(2, 5));
Return Statement
When we want to return some values from a function after performing some
operations, we make use of the return. This is an optional statement. In the
above function, “sum()” returns the sum of two as a result.
Function Parameters
Calling Functions
After defining a function, the next step is to call them to make use of the
function. We can call a function by using the function name separated by the
value of parameters enclosed between the parenthesis.
</script>
</body>
</html>
Explanation:
1. The function addNumbers(a, b) takes two parameters and returns
their sum.
2. The prompt() function is used to take user input, which is converted to
a number using parseFloat().
3. The function is called with the user inputs as arguments.
4. The result is displayed using console.log() and alert().
<!DOCTYPE html>
<html>
<body>
</script>
</body>
</html>
Example 3:
<!DOCTYPE html>
<html>
<body>
<h2>Calculate area and circumference of circle </h2>
<script>
// Function to calculate the area of a circle
function calculateArea(radius) {
return Math.PI * radius * radius;
}
// Function calls
let area = calculateArea(radius);
let perimeter = calculatePerimeter(radius);
alert("The area of the circle is: " + area.toFixed(2) + "\nThe perimeter is: " +
perimeter.toFixed(2));
</script>
</body>
</html>
Explanation:
1. calculateArea(radius) – Computes the area using the formula:
Area=π×r2
2. calculatePerimeter(radius) – Computes the perimeter using the
formula: Perimeter=2×π×r
3. prompt() gets the radius from the user.
4. The functions are called with the user input.
5. The results are displayed using console.log() and alert().
6. toFixed(2) rounds the output to 2 decimal places.
Why Functions?