JavaScript Basics: Interactive Web Programming
JavaScript Basics: Interactive Web Programming
JavaScript is a versatile, dynamically typed programming language used for interactive web
applications, supporting both client-side and server-side development, and integrating
seamlessly with HTML, CSS, and a rich standard library.
• The data type of the variable is decided at run-time in JavaScript that’s why it is
called dynamically typed.
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
[Link]("Hello, World from console..!");
alert("Hello, World from alert..!");
</script>
</body>
</html>
In this example
The <script> tag is used to include JavaScript code inside an HTML document.
[Link]() prints messages to the browser’s developer console. Open the browser
console to see the “Hello, World!” message.
[Link]("Hello, World from the console..!"); // Prints Hello, World! to the console
In this example
• Versatile: JavaScript can be used for a wide range of tasks, from simple
calculations to complex server-side applications.
• Asynchronous: JavaScript can handle tasks like fetching data from servers without
freezing the user interface.
• Rich Ecosystem: There are numerous libraries and frameworks built on JavaScript,
such as React, Angular, and [Link], which make development faster and more
efficient.
Client Side and Server Side nature of JavaScript
• Client-side: Involves controlling the browser and its Document Object Model
(DOM), handling user events like clicks and form inputs. Libraries such as
AngularJS, ReactJS, and VueJS are commonly used.
• Declarative Programming: Focuses on what should be done rather than how it’s
done. It emphasizes describing the desired result, like with arrow functions, without
detailing the steps to achieve it.
Applications of JavaScript
• Game Development: JavaScript, combined with HTML5 and libraries like Ease JS,
enables the creation of interactive games for the web.
Limitations of JavaScript
• Security Risks : JavaScript can be used for attacks like Cross-Site Scripting (XSS),
where malicious scripts are injected into a website to steal data by exploiting
elements like <img>, <object>, or <script> tags.
• Performance : JavaScript is slower than traditional languages for complex tasks,
but for simple tasks in a browser, performance is usually not a major issue.
• Weak Error Handling and Type Checking : JavaScript is weakly typed, meaning
variables don’t require explicit types. This can lead to issues as type checking is not
strictly enforced.
JavaScript is both compiled and interpreted. The V8 engine improves performance by first
interpreting code and then compiling frequently used functions for speed. This makes
JavaScript efficient for modern web apps. It’s mainly used for web development but also
works in other environments.
• Hot Code Detection: The engine identifies frequently executed code, such as often-
called functions.
• Compilation: The “hot” code is compiled into optimized machine code for faster
execution.
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.
To add JavaScript in HTML document, several methods can be used. These methods
include embedding JavaScript directly within the HTML file or linking an external
JavaScript file.
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 Button Clicked..!')"> Click Here </button>
</body>
</html>
2. Internal JavaScript (Within <script> Tag)
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.
Placing JavaScript within the <head> section of an HTML document ensures that the script
is loaded and executed as the page loads. This is useful for scripts that need to be
initialized before the page content is rendered.
<html>
<head>
<script>
function myFun() {
[Link]("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" Click Here </button>
</body>
</html>
JavaScript can also be placed inside the <body> section of an HTML page. Typically, scripts
placed at the end of the <body> load after the content, which can be useful if your script
depends on the DOM being fully loaded.
<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" Click Here </button>
<script>
function myFun() {
[Link]("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="[Link]"></script>
</head>
<body>
<h2> External JavaScript </h2>
<h3 id="demo" style="color:green;"> To demonstrate External JavaScript </h3>
<button type="button" Click Here </button>
</body>
</html>
JavaScript:
/* Filename: [Link]*/
function myFun () {
[Link]('demo')
}
Advantages of External JavaScript
• 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.
• Code Reusability: One external JavaScript file can be linked to multiple HTML files,
reducing redundancy and making updates easier.
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="[Link]" 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="[Link]" defer></script>
1. Using innerHTML
<!DOCTYPE html>
<html>
<body>
<h2>Inner HTML output</h2>
<p id="demo"></p>
<script>
[Link]("demo").innerHTML = 5 + 6;
</script>
</body>
</html>
2. Using [Link]()
<!DOCTYPE html>
<html>
<body>
<h2>Using [Link]</h2>
<script> [Link](5 + 6); </script>
</body>
</html>
Note: Using [Link]() after an HTML document is loaded, will delete all existing
HTML. Thus [Link]() method should only be used for testing. E.g.
<!DOCTYPE html>
<html>
<body>
<h2>Using [Link] - deletes html </h2>
<p>Other html data that will be deleted also </p>
<button type="button" + 6)">Click Here </button>
</body>
</html>
3. Using [Link]()
<!DOCTYPE html>
<html>
<body>
<h2>Using windows alert </h2>
<script>
[Link](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 [Link]()
For debugging purposes, you can call the [Link]() 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 [Link]() 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 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. [Link]("demo").innerHTML = "Internet application
Programming.";
The statements are executed, one by one, in the same order as they are written.
JavaScript statements often start with a keyword to identify the JavaScript action to be
performed. E.g.
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.
JavaScript Events are actions or occurrences that happen in the browser. They can be
triggered by various user interactions or by the browser itself. E.g.
<html>
<script>
function myFun() {
[Link](
"iap").innerHTML = "Click event triggered, for Internet Application
Programming";
}
</script>
<body>
<button me </button>
<p id="iap"></p>
</body>
</html>
• The onclick attribute in the <button> calls the myFun() function when clicked.
• The myFun() function updates the <p> element with id=”iap” by setting its
innerHTML to “Click event triggered, for Internet Application Programming”.
• Initially, the <p> is empty, and its content changes dynamically on the button click.
Event Types:
<html>
<body>
<h2> Inline HTML Handlers </h2>
<button clicked!')">Click Me</button>
</body>
</html>
2. DOM Property Handlers
3. addEventListener() (Preferred)
[Link]("click", () => {
alert("Button clicked using addEventListener!");
});
addEventListener() is the most versatile and recommended method as it supports
multiple event listeners and removal of listeners.
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>
[Link]("#formval").addEventListener("submit", (e) => {
let input = [Link]("#formInput");
if (![Link]) {
[Link]();
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
Identifiers can be short names like x and y or more descriptive names (age, sum,
totalVolume).
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";
[Link]("demo").innerHTML = carName;
</script>
You can declare many variables in one statement by starting the statement with let and
separate the variables by comma:
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Variables</h1>
<p>You can declare many variables in one statement.</p>
<p id="demo"></p>
<p id="demo1"></p>
<p id="demo2"></p>
<script>
let course = "BIT", unit_code = " BIT 04204 ", unitName ="Internet Application
Programming";
[Link]("demo").innerHTML = course;
[Link]("demo1").innerHTML = unit_code;
[Link]("demo2").innerHTML = unitName;
</script>
</body>
</html>
Global and Local variables in JavaScript
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 [Link]).
• Scope: Accessible throughout the entire script, including inside functions and
blocks.
Example:
<!DOCTYPE html>
<html>
<head><title>Global Variables</title></head>
<body>
<script>
let petName = 'Jimmy' // Global variable
myFunction()
function myFunction() {
fruit = 'apple'; // Considered global
[Link]('My pet name is ' + petName + ' - from global')
}
[Link]('My pet name is ' + petName +'.' + ' Fruit name is ' + fruit + ' -
Considered global')
</script>
</body>
</html>
Explanation: We can see that the variable petName is declared in the global scope and is
easily accessed inside functions. Also, the fruit was declared inside the function without
any keyword so it was considered global and was accessible inside another function.
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
[Link](petName);
}
function anotherFunc() {
let petName = "Jimmy"; // local variable
[Link](petName);
}
[Link](petName);
</script>
</body>
</html>
Discuss when to use either const, var, or let in JavaScript variable declaration?.
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 '));
</body>
</html>
<!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: ');
JavaScript Operators
JavaScript operators are symbols or keywords used to perform operations on values and
variables. They are the building blocks of JavaScript expressions and can manipulate data
in various ways.
1. Arithmetic Operators
Used to assign values to variables. They can also perform operations like addition or
multiplication before assigning the value.
Comparison operators compare two values and return a boolean (true or false). They are
essential tools for checking conditions and making decisions in your code.
== compares values with type coercion, meaning it converts both values to a common type
before comparing.
=== 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.
The ternary operator is a shorthand for conditional statements. It takes three operands.
The Ternary Operator in JavaScript is a shortcut for writing simple if-else statements. It’s
also known as the Conditional Operator because it works based on a condition. The ternary
operator allows you to quickly decide between two values depending on whether a
condition is true or false.
[Link](res);
Comma Operator (,) mainly evaluates its operands from left to right sequentially and
returns the value of the rightmost operand.
The comma operator is often used in for loops to include multiple expressions within the
loop initialization or increment sections. It can also be used in variable assignments and
other contexts where multiple operations need to be performed in sequence. Also used to
include multiple expressions in a single variable declaration statement, but only the last
expression’s value will be assigned to the variable.
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
true
false
false
In JavaScript,
JavaScript String Operators include concatenation (+) and concatenation assignment (+=),
used to join strings or combine strings with other data types. E.g.
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);
[Link](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) {
[Link]("age").innerHTML = "You are a Young person. !";
}
</script>
</body>
</html>
Use the else statement to specify a block of code to be executed if the condition is false.
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) {
[Link]("age").innerHTML = "You are a Young person. !";
}
else {
[Link]("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";
}
[Link]("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
The For Loop
The for statement creates a loop with 3 optional expressions:
Syntax:
for (initialization; condition; increment/decrement) {
// Code to execute
}
Example:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript for loop</h2>
<script>
//let i = 5;
for (let i = 1; i <= 5; i++) {
[Link]("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>
<h2>JavaScript For In Loop</h2>
<p id="id1"></p>
<script>
const person = {fname:"John", lname:"kamau", age:24};
let txt = "";
for (let x in person) {
txt += person[x] + " ";
}
[Link]("id1").innerHTML = txt;
</script>
</body>
</html>
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>";
}
[Link]("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) {
[Link](count);
count++;
}
</script>
</body>
</html>
Output:
1
2
3
4
5
5. JavaScript do-while Loop
The do-while loop is similar to while loop except it executes the code block at least once
before checking the condition.
• Entry Controlled loops: The test condition is tested before entering the loop
body. For Loop and While Loops are entry-controlled loops.
• Exit Controlled Loops: The test condition is tested or evaluated at the end of the
loop body. Therefore, the loop body will execute at least once, irrespective of
whether the test condition is true or false. The do-while loop is exit controlled loop.
Syntax:
do {
// Code to execute
} while (condition);
Example:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript do while loop</h2>
<script>
let test = 1;
do {
[Link](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> <h2>Right-Angled Triangle using while loop </h2>
<script> <script>
let rows = parseInt(prompt("Enter the let rows = parseInt(prompt("Enter the number of
number of rows:")); rows:"));
let pattern = ""; let i = 1;
let pattern = "";
for (let i = 1; i <= rows; i++) {
for (let j = 1; j <= i; j++) { while (i <= rows) {
pattern += "* "; let j = 1;
} while (j <= i) {
pattern += "\n"; pattern += "* ";
} j++;
[Link](pattern); }
alert(pattern); pattern += "\n";
i++;
</script> }
</body> [Link](pattern);
</html> alert(pattern);
</script>
</body>
</html>
<h2>Number Pyramid using for loop </h2> <h2>Pyramid Pattern using while Loop </h2>
<script> <script>
let rows = parseInt(prompt("Enter the number let rows = parseInt(prompt("Enter the number of
of rows:")); 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 += "*";
[Link](pattern); stars++;
alert(pattern); }
pattern += "\n";
</script> i++;
</body> }
</html> [Link](pattern);
alert(pattern);
</script>
</body>
</html>
[Link](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;
}
[Link](sum(2, 5));
• A user-defined function name (In the above example, the name is sum)
• A list of parameters enclosed within parentheses and separated by commas (In the
above example, parameters are x and y)
• A list of statements composing the body of the function enclosed within curly
braces {} (Such as, “return x + y”).
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
Parameters are input passed to a function. In the above example, sum() takes two
parameters, x and y.
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 [Link]() 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 [Link] * radius * radius;
}
// Function calls
let area = calculateArea(radius);
let perimeter = calculatePerimeter(radius);
alert("The area of the circle is: " + [Link](2) + "\nThe perimeter is: " +
[Link](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 [Link]() and alert().
6. toFixed(2) rounds the output to 2 decimal places.
Why Functions?
• Functions can be used multiple times, reducing redundancy.
Function invocation and function call. Differentiate the two as used in JavaScript.