0% found this document useful (0 votes)
4 views

JavaScript-2

The document provides an overview of JavaScript functions, including their definition, syntax, and usage in various examples such as calculating squares, finding maximum values, and generating random images. It also covers recursion, array declarations, and passing arrays to functions, highlighting the flexibility of JavaScript in handling different data types and structures. Additionally, it includes practical code snippets demonstrating these concepts in action.

Uploaded by

phtkgmz
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

JavaScript-2

The document provides an overview of JavaScript functions, including their definition, syntax, and usage in various examples such as calculating squares, finding maximum values, and generating random images. It also covers recursion, array declarations, and passing arrays to functions, highlighting the flexibility of JavaScript in handling different data types and structures. Additionally, it includes practical code snippets demonstrating these concepts in action.

Uploaded by

phtkgmz
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 45

UNIT II

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).

Passing Array to Function as Pass by Reference


Ex:create a JavaScript program in which we will pass an initialized array to a function. Then, we
will multiply each array element by 5 and display it.
<script>
let nums = new Array(20, 10, 25, 15, 35, 40);
let arrayLength = nums.length;
document.write("Original array elements are: ", "<br/>");

for(i = 0; i < arrayLength; i++) {


document.write(nums[i]+ " ");
}
document.write("<hr>");
// Function to pass an array by reference.
function modifyArray(x) {
document.write("Modified array elements: ", "<br/>");
for(i = 0; i < arrayLength; i++) {
document.write(nums[i] * 5 + " ");
}
}
// Calling function by passing array.
modifyArray(nums); // entire array passed by reference.
</script>
Passing Individual Array Element to Function as Pass by Value
create a JavaScript program in which we will pass the entire array as a pass by reference to the function in JavaScript.
Then we will pass the individual array element to the function as a pass by value in JavaScript.
<script>
let nums = [10, 20, 30, 40, 50];
document.write("Original array: ", "<br/>");
for(i = 0; i < nums.length; i++)
document.write(nums[i]+ " ");
document.write("<br/>");
document.write("Modified array: ", "<br/>");
// Create a function that modifies elements of an array.
function modifyArray(newArray) {
for(j = 0; j < nums.length; j++)
document.write((newArray[j] *= 4)+ " ");
}
modifyArray(nums); // passing an array as passed by reference.
document.write("<br/>");
document.write("nums[3] before modifyElement: " +nums[3], "<br/>");
// Create a function that modifies the value passed.
function modifyElement(e) {
e *= 3;
document.write("nums[3] after modifyElement: " +e);
}
modifyElement(nums[3]); // passing array element nums[3] as passed by value.
Sorting Arrays with Array Method sort
The sort() method allows you to sort elements of an array in place. Besides returning the sorted array, the sort()
method changes the positions of the elements in the original array.
By default, the sort() method sorts the array elements in ascending order with the smallest value first and largest
value last.
The sort() method casts elements to strings and compares the strings to determine the orders.
Consider the following example:
let numbers = [0, 1 , 2, 3, 10, 20, 30 ];
numbers.sort();
document.write(numbers); o/p: [ 0, 1, 10, 2, 20, 3, 30 ]
array.sort(comparefunction)
function compare(a,b) { // ... }
The compare() function accepts two arguments a and b. The sort() method will sort elements based on the return
value of the compare() function with the following rules:
If compare(a,b) is less than zero, the sort() method sorts a to a lower index than b. In other words, a will come first.
If compare(a,b) is greater than zero, the sort() method sort b to a lower index than a, i.e., b will come first.
If compare(a,b) returns zero, the sort() method considers a equals b and leaves their positions unchanged.
<!DOCTYPE html>
// comparison function for use with sort
<html>
function compareIntegers( value1, value2 )
<head>
<title>Array Method sort</title> {
<script> return parseInt( value1 ) - parseInt( value2 );
function start() { } // end function compareIntegers
var a = [ 10, 1, 9, 2, 8, 3, 7, 4, 6, 5 ]; window.addEventListener( "load", start,
outputArray( "Data items in original order: ", a, false );
document.getElementById( "originalArray" ) ); </script>
a.sort( compareIntegers ); // sort the array
</head>
outputArray( "Data items in ascending order: ", a,
<body>
document.getElementById( "sortedArray" ) );
} // end function start <h1>Sorting an Array</h1>
function outputArray( heading, theArray, output ) <p id = "originalArray"></p>
{ <p id = "sortedArray"></p>
output.innerHTML = heading + theArray.join( " </body>
" );
</html>
Searching Arrays with Array Method indexOf
When working with data stored in arrays, it’s often necessary to determine whether an array contains a
value that matches a certain key value. The process of locating a particular element value in an array is
called searching.
The Array object in JavaScript has built-in methods indexOf and lastIndexOf for searching arrays
Method indexOf searches for the first occurrence of the specified key value,
Method lastIndexOf searches for the last occurrence of the specified key value. If the key value is found
in the array, each method returns the index of that value; otherwise, -1 is returned.
<html> else
<head> {
<title>Search an Array</title> result.innerHTML = "Value not found";
<script> } // end else
var a = new Array( 100 ); // create an array } // end function buttonPressed
for ( var i = 0; i < a.length; ++i ) // register searchButton's click event handler
{ function start()
a[ i ] = 2 * i; {
} // end for var searchButton = document.getElementById( "searchButton" );
// function called when "Search" button is pressed searchButton.addEventListener( "click", buttonPressed, false );
function buttonPressed() } // end function start
{ window.addEventListener( "load", start, false );
// get the input text field </script>
var inputVal = document.getElementById( "inputVal" ); </head>
// get the result paragraph <body>
var result = document.getElementById( "result" ); <p><label>Enter integer search key:
var searchKey = parseInt( inputVal.value ); <input id = "inputVal" type = "number"></label>
var element = a.indexOf( searchKey ); <input id = "searchButton" type = "button" value = "Search">
if ( element != -1 ) </p>
{ <p id = "result"></p>
</body>
result.innerHTML = "Found value in element " + element;
</html>
Multidimensional Arrays
A multidimensional array in javascript is an array that has one or more nested arrays.
A normal array, is a one-dimensional array that can be accessed using a single
index, arr[i] where as a two-dimensional array can be accessed using two indices, arr[i][j],
Similarly for three-dimensional array arr[i][j][k] and so on.
a multidimensional array is known as an array of arrays and It holds a matrix of elements as
shown in the image below.

Creating a Multidimensional Array


A multidimensional array is not present natively in JavaScript. Hence there is no direct way to
create a multidimensional array in JavaScript.
However, We can define an array of elements to create a multi-dimensional array in such a way
so that each element stored in an array is also another array.
There are two ways to create a multidimensional array in JavaScript:
Using array literal: The quickest way to create a Multi-Dimensional Array in JavaScript is to use the
array literal notation.
var Employee = [
[20, 'Pranshu', 'Lucknow'],
[21, 'Sameer', 'Vanaras'],
[22, 'Kartikey', 'Lakhimpur']
]
Using array constructor: Another way is to use an an array constructor. This is done by using
the Array() method.
var Employee = Array(
[20, 'Pranshu', 'Lucknow'],
[21, 'Sameer', 'Vanaras'],
[22, 'Kartikey', 'Lakhimpur']
)
To add two matrices in JavaScript // To store result
<script>
// Javascript program for addition of two matrices
let C = new Array(N);
let N = 4; for (let k = 0; k < N; k++)
// This function adds A[][] and B[][], and stores the result in C[][]
C[k] = new Array(N);
function add(A, B, C)
{ let i, j;
let i, j;
add(A, B, C);
for (i = 0; i < N; i++)
for (j = 0; j < N; j++) document.write("Result matrix is <br>");
C[i][j] = A[i][j] + B[i][j]; for (i = 0; i < N; i++)
}
{
let A = [ [4, 5, 1, 8], for (j = 0; j < N; j++)
[2, 5, 8, 9],
[3, 3, 3, 3], document.write(C[i][j] + " ");
[7, 8, 4, 5]]; document.write("<br>");
let B = [ [4, 1, 8, 12],
}
[2, 2, 2, 2],
[11, 33, 38, 39],
[7, 5, 4, 2]];
</script>
Javascript program to multiplytwo square matrices. let mat1 = [ [ 10, 11, 16, 18 ],
<script> [ 7, 5, 22, 24 ],
const N = 4;
[ 8, 3, 9, 35 ],
// This function multiplies mat1[][] and mat2[][], and stores the
result in res[][] [ 2, 4, 7, 8 ] ];
function multiply(mat1, mat2, res)
{
let mat2 = [ [ 7, 5, 8, 9 ],
let i, j, k;
[ 7, 8, 22, 5 ],
for (i = 0; i < N; i++) {
for (j = 0; j < N; j++) { [ 11, 4, 8, 7 ],
res[i][j] = 0; [ 7, 5, 9, 6 ] ];
for (k = 0; k < N; k++)
res[i][j] += mat1[i][k] * mat2[k][j];
multiply(mat1, mat2, res);
}
document.write("Result matrix is <br>");
}
} for (i = 0; i < N; i++) {
for (j = 0; j < N; j++)
let i, j; document.write(res[i][j] + " ");
let res = new Array(N); document.write("<br>");
for (let k = 0; k < N; k++)
}
res[k] = new Array(N);
JavaScript: Objects
• A javaScript object is an entity having state and behavior (properties and method).
• JavaScript is an object-based language. Everything is an object in JavaScript.
• JavaScript is template based not class based. Here, we don't create class to get the object. But, we
direct create objects.
Math Object
String Object
Date Object
Boolean and Number Objects
document Object
Math Object
The JavaScript Math is a built-in object that provides properties and methods for mathematical constants
and functions to execute mathematical operations.
Following is the list of methods used with the Math object:
Math.round(), Math.pow(), Math.sqrt(), Math.abs(), Math.ceil(), Math.floor(), Math.sin(),
Math.cos(), Math.min() and Math.max(), Math.random(), Math.acos(), Math.asin()
Math.round() <!DOCTYPE html>
This method provides the value of the given <html> <body>
number to a rounded integer. It can be written as:
Math.round(x), where x is a number. <p id="abs_demo"></p>
Math.pow() <script>
It provides the value of x to the power of y. It can document.getElementById("abs_demo").innerHTM
be written as: L = Math.abs(-5.6);
Math.pow(x, y), where x is a base number and y </script>
is an exponent to the given base.
</body>
Math.sqrt()
</html> o/p:5.6
It gives the square root of a given integer. It can
Math.ceil()
be written as:
Math.sqrt(x), where x is a number. It gives a smaller number, which is greater or equal
to the given integer. It can be written as:
Math.abs()
Math.ceil(x); where x is a number
It provides the absolute i.e. positive value of a
document.getElementById("ceil_demo").innerHT
number. It can be written as:
ML = Math.ceil(7.8);
Math.abs(x); where x is a number.
o/p:8
Math.floor() Math.cos()
It gives a larger number, which is lesser or equal to the It provides cosine of the given number.
given integer. It can be written as:Math.cos(x); where x is a number
It can be written as: Math.floor(x); where x is a number. var value = Math.cos(90); document.write("First Value :
document.getElementById("floor_demo").innerHTML " + value );
= Math.floor(7.8); o/p:7 Math.random()
Math.sin()
It provides a random number between 0 and 1.
It provides a sine of the given number. It can be written
as: Math.sin(x); where x is a number It can be written as:Math.random();
<html> var value = Math.random( ); document.write("First
Value : " + value );
<body>
Math.acos()
<script type = "text/javascript">
var value = Math.sin( 4.5 ); It provides an arccosine of an integer.
document.write("First Value : " + value ); It can be written as:Math.acos(x); where x is a number.
var value = Math.sin( 90 ); var value1 = Math.acos(-1); document.write("First Value
: " + value1 );
document.write("<br />Second Value : " + value );
var value2 = Math.acos(null); document.write("<br
</script> />Second Value : " + value2 );
</body> First Value : 3.141592653589793 Second Value : 1.5707963267948966
Math.min() and Math.max() Math.asin()
• The min() method is used to display the lowest value of • It provides arcsine of an integer.
the given arguments. It can be written as:
• It can be written as:Math.asin(x); where x
Math.min(val1, val2………valn); where val1,
is a number.
val2………valn are numbers.
var value1 = Math.asin(-1);
• The max() method is used to display the highest value of document.write("First Value : " + value1 );
the given arguments. It can be written as:
Math.max(val1, val2………valn); where val1,
var value2 = Math.asin(null);
document.write("<br />Second Value : " +
val2………valn are numbers.
value2 );
<html><body>
First Value : -1.5707963267948966 Second
Minimum Value: <p id="min_demo"></p>
Value : 0
Maximum Value: <p id="max_demo"></p>
<script>
document.getElementById("min_demo").innerHTML
=Math.min(40, 87, 55, 25, 78, 14);
document.getElementById("max_demo").innerHTML
=Math.max(50, 90, 55, 25, 78, 14);
</script></body></html>
properties used with Math object SQRT2- It specifies the square root of 2.
E- It specifies Euler’s number. var value_demo = Math.SQRT2
<html> The value is:1.1414213562
<body> SQRT1_2- It specifies the square root of 1/2.
<script type = "text/javascript"> var value_demo = Math.SQRT1_2
var value_demo = Math.E The value is: 0.707106
document.write("The Value is :" + value_demo); LN2- It specifies the natural logarithm of 2.
</script> var value_demo = Math.LN2
</body> The value is: 0.6931471805
</html> LOG2E – It specifies the BASE 2 logarithm of E.
The Value is :2.718281828459045 var value_demo = Math.LOG2E
PI- It provides PI value. The value is: 1.442695040
var value_demo = Math.PI
The value is: 3.14159265
String Object IndexOf()
A string in Javascript can be created using double • It will search and will return the index of the first
quotes or single quotes. occurrence of a mentioned character or substring
We can create a string by a string literal or by the within the string. If mentioned character or
use of a new keyword(string object). substring is not found, it will return -1.
• In case of a string literal, the use of double <html>
quotes can help you create a string, given the <body>
syntax- <script>
var typeStringNameHere = "You created a string var st = "Please only find where 'only' occurs!";
literal";
var po = st.indexOf("only");
• In case of a string object, the use of new
keyword can help you create a string, given the document.write("<br />position : " + po);
following syntax- </script>
var typeStringNameHere = new String("You </body>
created a string object");
</html> o/p:7
lastIndexOf() slice()
• This JavaScript String will search and return the This string function in JavaScript is used to trims a
index of the last occurrence of a mentioned part of a string and returns the trimmed part in a
character or substring within the string. If newly created string.
mentioned character or substring is not found, it var string = "Mango, Apple, Kiwi";
will return -1
var r = string.slice(7, 12); o/p: Apple
var st = "Please only find where 'only' occurs!";
substring()
var po = st.lastindexOf("only "); o/p:23
• It is the same as the slice() method. The only
search() difference is that substring() does not accept
It will search and test for a match in a string and negative indexes.
returns the index of the match. If mentioned var s = "Apple, Banana, Kiwi";
character or substring is not found, it will return - var r = s.substring(7, 13); o/p:Banana
1.
substr()
var st = "Please only find where 'only' occurs!";
• It is the same as the slice() method. The only
var po = st.search("only"); o/p:7 difference is that in substr() the second parameter
The difference between the search() method and denotes the length of the first, that is extracted
indexOf() method is that the search() method parameter
cannot take the second argument and var s = "Apple, Kiwi";
indexOf() method cannot take regular expressions.
replace(x,y) var r = str.charCodeAt(0);
• This method replaces the first parameter(x) with The result of r will be: 72
the second parameter(y) in the string:
toLowerCase()
var s = "Please visit Oracle!";
• This JavaScript string function will Return the
var n = s.replace("Oracle", "Microsoft"); string with all the characters converted to
The result of n will be: Please visit Microsoft! lowercase.
charAt(y) var m = 'PYTHON';
• Returns the character that is located at the “y” var r = m.toLowerCase();
position in the string. The result of r will be: python
var s = "WORLD"; toUpperCase()
var r = s.charAt(3); • This JavaScript string function will Return the
The result of r will be: L string with all the characters converted to
uppercase.
charCodeAt(y)
var m = "python";
• This method will return the Unicode value of the
character that is located at position “y” in the var r = m.toUpperCase();
string. The result of r will be: PYTHON
var str = "Halloween";
concat(v1, v2,…) var s = "Hello guys"; var
• This method will combine one or more than one n = s.startsWith("Hello");
string into the original one and return the
concatenated string. Original string won’t be The result of n will be: TRUE
modified. split(delimiter)
var t1 = "Hi"; • This method will split a string into array items as per
var t2 = "What’s up!"; the specified parameter (delimiter) and returns an
array consisting of each element.
var t3 = t1.concat(" ", t2);
var message="Welcome to hell !"
The result of t3 will be: Hi What’s up!
trim() var word=message.split("t");
• This method will remove any whitespaces from both word[0] contains “Welcome” and word[1] contains “ to
the start and end of a string: hell !”
var s = " Hi What’s up! "; endsWith()
var b = s.trim()); • This method finds out if the string is ending with the
characters of a mentioned string. This method
The result of b will be: “Hi What’s up!” returns true if the string is ending with the characters
startsWith() provided, and false if not.
• This method finds out if the string is starting with var s = "Hello guys";
the characters of a mentioned string. This method var n = s.endsWith("guys");
returns true if the string is starting with the The result of n will be: TRUE
toString()
• This method will return the String object value.
var string = "Hello guys!";
var r = string.toString();
The result of n will be: Hello guys!
length
• This will returns the number of characters that is the length of a string.
var string = "Hello People!";
var n = string.length;
The result of n will be: 12
Date object <html>
• The Date object is a datatype built into the <head>
JavaScript language. Date objects are created <title>JavaScript Date Method</title>
with the new Date( ) .
</head>
• Once a Date object is created, a number of
methods allow you to operate on it. <body>
• Most methods simply allow you to get and set <script type = "text/javascript">
the year, month, day, hour, minute, second, and var dt = Date();
millisecond fields of the object, using either
local time or based on World Time Standard’s document.write("Date and Time : " + dt );
Coordinated Universal Time (abbreviated UTC)- </script>
formerly called Greenwich Mean Time (GMT).
</body>
Date object methods
</html>
Date() method returns today's date and time and
o/p: Date and Time : Wed May 03 2023 13:27:39
does not need any object to be called.
GMT+0530 (India Standard Time)
• Syntax: Date()
getDate() method returns the day of the month for getHours() method returns the hour in the
the specified date according to local time. specified date according to local time. The value
The value returned by getDate() is an integer returned by getHours() is an integer between 0
between 1 and 31. and 23.
Date.getDate() Date.getHours()

getDay() method returns the day of the week for the


specified date according to local time. getMilliseconds() method returns the
milliseconds in the specified date according to
The value returned by getDay() is an integer local time. The value returned
corresponding to the day of the week: 0 for Sunday,
1 for Monday, 2 for Tuesday, and so on. by getMilliseconds() is a number between 0 and
999.
Date.getDay()
Date.getMilliseconds()
getFullYear() method returns the year of the
specified date according to local time. getMinutes() method returns the minutes in the
The value returned by getFullYear() is an absolute specified date according to local time. The value
number. For dates between the years 1000 and returned by getMinutes() is an integer between 0
9999, getFullYear() returns a four-digit number. and 59.
Date.getFullYear() Date.getMinutes()
getMonth() method returns the month <html>
in the specified date according to local <head>
time. The value returned
by getMonth() is an integer between 0 <title>JavaScript Date Method</title>
and 11. 0 corresponds to January, 1 to </head>
February, and so on. <body>
Date.getMonth() <script type = "text/javascript">
var dt = new Date();
document.write("getDate : " + dt.getDate() );
getTime() method returns the numeric
value corresponding to the time for the document.write("getTime : " + dt.getTime() );
specified date according to universal document.write("getFullYear : " + dt.getFullYear() );
time. The value returned by document.write("getHours : " + dt.getHours() );
the getTime method is the number of document.write("getMilliseconds : +dt.getMilliseconds() );
milliseconds since 1 January 1970
document.write("getMinutes : " + dt.getMinutes() );
00:00:00.
document.write("getMonth : " + dt.getMonth() );
Date.getTime()
</script>
</body>
setDate() method sets the day of the month for a setFullYear() method sets the full year for a specified
specified date according to local time. date according to local time.
Date.setDate( dayValue ) Syntax: Date.setFullYear(yearValue[,monthValue[,
dayValue]])
Ex: var dt = new Date( "Aug 28, 2008 23:30:00" );
<html>
dt.setFullYear( 2000 );
<head>
document.write( dt );
<title>JavaScript setDate Method</title>
o/p:Mon Aug 28 2000 23:30:00 GMT+0530 (India
</head> Standard Time)
<body> setHours() method sets the hours for a specified date
<script type = "text/javascript"> according to local time.
var dt = new Date( "Aug 28, 2008 23:30:00" Syntax: Date.setHours(hoursValue[,minutesValue[,
); secondsValue[, msValue]]])
dt.setDate( 24 ); Ex: var dt = new Date( "Aug 28, 2008 23:30:00" );
document.write( dt ); dt.setHours( 02 );
</script> document.write( dt );
</body> o/p:Thu Aug 28 2008 02:30:00 GMT+0530 (India
Standard Time)
setMinutes() method sets the minutes for a specified setSeconds() method sets the seconds for a
date according to local time. specified date according to local time
Syntax: Date.setMinutes(minutesValue[, Syntax:Date.setSeconds(secondsValue[, msValue])
secondsValue[, msValue]]) Ex: var dt = new Date( "Aug 28, 2008 23:30:00" );
Ex:var dt = new Date( "Aug 28, 2008 23:30:00" ); dt.setSeconds( 80 );
dt.setMinutes( 45 ); documentt.write( dt );
document.write( dt ); o/p:Thu Aug 28 2008 23:31:20 GMT+0530 (India
o/p:Thu Aug 28 2008 23:45:00 Standard Time)
setMonth() method sets the month for a specified toLocaleDateString() method converts a date
date according to local time.GMT+0530 (India to a string, returning the "date" portion using
Standard Time) the operating system's locale's conventions.
Syntax: Date.setMonth(monthValue[, dayValue]) Syntax: Date.toLocaleString()
Ex: var dt = new Date( "Aug 28, 2008 23:30:00" ); Ex: var dt = new Date(1993, 6, 28, 14, 39, 7);
dt.setMonth( 2 ); document.write( "Formated Date : " +
document.write( dt ); dt.toLocaleDateString() );
o/p: Fri Mar 28 2008 23:30:00 GMT+0530 (India o/p:Formated Date : 7/28/1993
Standard Time)
Boolean and Number Objects to String()
toSource() method returns a string representing the This method returns a string of either "true" or
source code of the object. "false" depending upon the value of the object.
Syntax: boolean.toSource() Syntax: boolean.toString()
Ex: <script type = "text/javascript"> Ex: var flag = new Boolean(10<5);
function book(title, publisher, price) { document.write( "flag.toString is : " +
this.title = title; flag.toString() );
this.publisher = publisher; o/p: flag.toString is : false
this.price = price;
}
var newBook = new book("Perl","Leo
Inc",200);
document.write(newBook.toSource());
o/p:({title:"Perl", publisher:"Leo Inc", price:200})
document Object getElementByTagName( tagName ) Returns an array of
the HTML5 elements with the specified tagName.
The document object, which we’ve used
extensively, is provided by the browser and allows <html><body>
JavaScript code to manipulate the current <h2>The getElementsByTagName() Method</h2>
document in the browser. <p>An unordered list:</p>
The document object has properties and methods <ul>
getElementById( id ) Returns the HTML5 element <li>Coffee</li>
whose id attribute matches id.
<li>Tea</li>
<html><body>
<li>Milk</li>
<h1>The Document Object</h1> </ul>
<h2>The getElementById() Method</h2> <p>The innerHTML of the second li element is:</p>
<p id="demo"></p> <p id="demo"></p>
<script> <script>
document.getElementById("demo").innerHTML = const collection =
"Hello World"; document.getElementsByTagName("li");
</script></body></html> document.getElementById("demo").innerHTML =
collection[1].innerHTML;

You might also like