JavaScript-2
JavaScript-2
JavaScript
JavaScript: Functions
• Functions are the basic building block of JavaScript. Functions allow us to encapsulate a block of code
and reuse it multiple times.
• Functions make JavaScript code more readable, organized, reusable, and maintainable.
A function is invoked (that is, made to perform its designated task) by a function call.
The function call specifies the function name and provides information (as arguments) that the called
function needs to perform its task
Syntax:
function <function-name>(arg1, arg2, arg3,...)
{
//write function code here
};
In JavaScript, a function can be defined using the function keyword, followed by the name of a function
and parentheses. Optionally, a list of input parameters can be included within the parentheses.
Function Definitions
A function definition (also called a function declaration, or function statement) consists of the function
keyword, followed by:
• The name of the function.
• A list of parameters to the function, enclosed in parentheses and separated by commas.
• The JavaScript statements that define the function, enclosed in curly brackets, { /* … */ }
For example, the following code defines a simple function named square:
function square(number) {
return number * number;
}
Ex1:
<html>
<head>
<title>A Programmer-Defined square Function</title>
<style type = "text/css">
p { margin: 0; }
</style>
<script>
document.writeln( "<h1>Square the numbers from 1 to 10</h1>" );// square the numbers from 1 to 10
for ( var x = 1; x <= 10; ++x )
document.writeln( "<p>The square of " + x + " is " + square( x ) + "</p>" );
function square( y )
{
return y * y;
} // end function square
</script>
</head><body></body> <!-- empty body element -->
</html>
<html>
<head>
<title>Maximum of Three Values</title>
<style type = "text/css">
p { margin: 0; }
</style>
<script>
var input1 = window.prompt( "Enter first number", "0" );
var input2 = window.prompt( "Enter second number", "0" );
var input3 = window.prompt( "Enter third number", "0" );
var value1 = parseFloat( input1 );
var value2 = parseFloat( input2 );
var value3 = parseFloat( input3 );
var maxValue = maximum( value1, value2, value3 )
document.writeln( "<p>First number: " + value1 + "</p>" + "<p>Second number: " + value2 + "</p>" + "<p>Third number: " + value3 + "</p>"
+
"<p>Maximum is: " + maxValue + "</p>" );
function maximum( x, y, z )
{
return Math.max( x, Math.max( y, z ) );
} // end function maximum
</script>
</head><body></body>
The random image generator
The random image generator concept is mostly used for advertisement. The images you see on a
website generating randomly, are already stored in a database or an array. These images display to the
user within a regular time interval or change by a click.
Steps for random image generator
• Create a database or Declare an array using JavaScript to store the images.
• Declare a JavaScript variable to store a random value calculated using
this floor(Math.random()*randomImage.length) method. It will generate a random number
between 0 and the length of the array that will be assigned to the images to display randomly.
• Now, return the random images selected using a number calculated in the previous step.
• Put all the above steps in a user-defined function (getRandomImage), which will call by clicking on
a Generate Image
• In HTML code, we will use a tab and provide an ID to display an image over another image. So, the
images will show you one by one, by overwrapping each other .
<html><head>
<title>Random Dice Images</title>
// set image source for a die
<style type = "text/css"> function setImage( dieImg )
li { display: inline; margin-right: 10px; } {
ul { margin: 0; } var dieValue = Math.floor( 1 + Math.random() * 6 );
</style>
dieImg.setAttribute( "src", "die" + dieValue + ".png" );
<script>
// variables used to interact with the img elements dieImg.setAttribute( "alt",
var die1Image; "die image with " + dieValue + " spot(s)" );
var die2Image; } // end function setImage
var die3Image;
window.addEventListener( "load", start, false );
var die4Image;
function start()
</script>
{ </head>
var button = document.getElementById( "rollButton" ); <body>
button.addEventListener( "click", rollDice, false ); <form action = "#">
die1Image = document.getElementById( "die1" );
<input id = "rollButton" type = "button" value = "Roll Dice">
die2Image = document.getElementById( "die2" );
die3Image = document.getElementById( "die3" ); </form>
die4Image = document.getElementById( "die4" ); <ol>
} // end function rollDice <li> <img id="die1" src="blank.png" alt="die1 image"></li>
// roll the dice
<li> <img id="die2" src="blank.png" alt="die2 image"></li>
function rollDice()
{
<li><img id="die3" src="blank.png" alt="die3 image"> </li>
setImage( die1Image ); <li><img id="die4" src="blank.png" alt="die4 image"> </li>
setImage( die2Image ); </ol>
setImage( die3Image ); </body>
setImage( die4Image );
</html>
# random – image generator
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<img src="pic1.jpg" id="image" alt="image" width="500" height="500"/>
<button id="btn">generate_image</button>
<script>
document.querySelector("#btn").addEventListener("click",()=>{
const img = document.querySelector("#image")
var index = Math.floor(Math.random()*4)
img.setAttribute("src","pic"+index+".jpg")
})
</script>
</body>
</html>
Recursion
A recursive function is a function that calls itself until it doesn’t. And this technique is called recursion.
Suppose that you have a function called recurse(). The recurse() is a recursive function if it calls itself inside its
body, like this:
function recurse()
{
// ... recurse(); // ...
}
A recursive function always has a condition to stop calling itself. Otherwise, it will call itself indefinitely. So a
recursive function typically looks like the following:
function recurse() {
if(condition) {
// stop calling itself
//...
} else {
recurse();
}
}
Write a JavaScript program to calculate the factorial of a // Recursive definition of function factorial
number.
function factorial( number )
In mathematics, the factorial of a non-negative integer n,
{
denoted by n!, is the product of all positive integers less than or
equal to n. For example, 5! = 5 x 4 x 3 x 2 x 1 = 120 if ( number <= 1 ) // base case
<html> return 1;
<head> else
<title>Recursive Factorial Function</title>
return number * factorial( number - 1 );
<style type = "text/css">
} // end function factorial
p { margin: 0px; }
</style> window.addEventListener( "load",
calculateFactorials, false )
<script>
var output = ""; // stores the output </script>
// calculates factorials of 0 - 10 </head>
function calculateFactorials() <body>
{ <h1>Factorials of 0 to 10</h1>
for ( var i = 0; i <= 10; ++i )
<div id = "results"></div>
output += "<p>" + i + "! = " +factorial(i)+ "</p>";
</body>
document.getElementById( "results" ).innerHTML = output;
</html>
JavaScript: Arrays
An array is a group of memory locations that all have the same name and normally are of the same
type.
To refer to a particular location or element in the array, we specify the name of the array and the
position number of the particular element in the array.
A JavaScript array has the following characteristics:
• First, an array can hold values of mixed types. For example, you can have an array that stores
elements with the types number, string, boolean, and null.
• Second, the size of an array is dynamic and auto-growing.
Declaring and Allocating Arrays
new Array() Constructor
Arrays occupy space in memory. JavaScript allows you to omit the new operator when you use the Array()
constructor.
The new operator creates an object as the script executes by obtaining enough memory to store an object of
the type specified to the right of new.
• let x = new Array(); - an empty array
• let x = new Array(10,20,30); - three elements in the array: 10,20,30
• let x = new Array(10); - ten empty elements in array: ,,,,,,,,,
• let x = new Array('10'); - an array with 1 element: ‘10’
The Literal Notation
Instead of new Array() , you can use square brackets []. Using square brackets is called the "array literal
notation":
let x = []; - an empty array
let x = [10]; - initialized array
let x = [10,20,30]; - three elements in the array: 10,20,30
let x = ["10", "20", "30"]; - declares the same: ‘10’,’20’,’30’
<!DOCTYPE html>
<html>
<body>
<h1>Demo: JavaScript Arrays</h1>
<p id="p1"></p>
<p id="p2"></p>
<p id="p3"></p>
<p id="p4"></p>
<p id="p5"></p>
<script>
let stringArray = ["one", "two", "three"];
let numericArray = [1, 2, 3, 4];
let decimalArray = [1.1, 1.2, 1.3];
let booleanArray = [true, false, false, true];
let data = [1, "Steve", "DC", true, 255000, 5.5];
document.getElementById("p1").innerHTML = stringArray;
document.getElementById("p2").innerHTML = numericArray;
document.getElementById("p3").innerHTML = decimalArray;
document.getElementById("p4").innerHTML = booleanArray;
document.getElementById("p5").innerHTML = data;
</script>
</body>
function start()
{
var colors = new Array( "cyan", "magenta","yellow", "black" );
var integers1 = [ 2, 4, 6, 8 ];
var integers2 = [ 2, , , 8 ];
outputArray( "Array colors contains", colors,
document.getElementById( "output1" ) );
outputArray( "Array integers1 contains", integers1,
document.getElementById( "output2" ) );
outputArray( "Array integers2 contains", integers2,
document.getElementById( "output3" ) );
} // end function start
function outputArray( heading, theArray, output )
{
var content = "<h2>" + heading + "</h2><table>" +
"<thead><th>Index</th><th>Value</th></thead><tbody>";
// output the index and value of each array element
var length = theArray.length; // get array's length once before loop
for ( var i = 0; i < length; ++i )
{
content += "<tr><td>" + i + "</td><td>" + theArray[ i ] +
"</td></tr>";
} // end for
content += "</tbody></table>";
output.innerHTML = content; // place the table in the output element
} // end function outputArray
window.addEventListener( "load", start, false );
<html>
<head>
<title>Initializing an Array</title>
<link rel = "stylesheet" type = "text/css" href = "tablestyle.css">
<script src = "InitArray2.js"></script>
</head>
<body>
<div id = "output1"></div>
<div id = "output2"></div>
<div id = "output3"></div>
</body>
</html>
Random Image Generator Using Arrays
Steps for random image generator
• Declare an array using JavaScript to store the images.
• Provide the link or URL of images in the declared array. You can also pass the height and width in the
array for the image size to display on the webpage.
• Declare a JavaScript variable to store a random value calculated using
this floor(Math.random()*randomImage.length) method. It will generate a random number between
0 and the length of the array that will be assigned to the images to display randomly.
• Now, return the random images selected using a number calculated in the previous step.
• Put all the above steps in a user-defined function (getRandomImage), which will call by clicking on
a Generate Image
• In HTML code, we will use a tab and provide an ID to display an image over another image. So, the
images will show you one by one, by overwrapping each other.
<html> for (let i=0; i< 5; i++) {
<head> //generate a number and provide to the image to generate
randomly
<title> Random Image Generator </title>
var number =
</head> Math.floor(Math.random()*randomImage.length);
<script> //print the images generated by a random number
function getRandomImage() { document.getElementById("result").innerHTML += '<img
src="'+ randomImage[number] +'" style="width:150px" />';
//declare an array to store the images
}
var randomImage = new Array();
}
//insert the URL of images in array </script>
randomImage[0] = "die1.png"; <body>
randomImage[1] = "die2.png"; <button onclick = "setInterval(getRandomImage, 2000)">
randomImage[2] = "die3.png"; Generate Image </button>
randomImage[3] = "die4.png"; <br> <br>
randomImage[4] = "die5.png"; <span id="result" align="center"> </span>
</body>
randomImage[5] = "die6.png";
</html>
//loop to display five randomly chosen images at once
Passing Arrays to Functions
• To pass an array argument to a function, simply pass the name of an array (a reference to an
array) without brackets.
For example, if we have declared an array marks as:
let hourlyTemp = new Array(30);
then function call statement: modifyArray(hourlyTemp);
passes array hourlyTemp to the function modifyArray(). JavaScript automatically passes arrays
to functions using call-by-reference (or passed by reference).