We Offer 100% Job Guarantee Courses (Any Degree / Diploma Candidates / Year GAP / Non-IT / Any Passed Outs). Placement Records
Hire Talent (HR):+91-9707 240 250

JavaScript Tutorial

JavaScript Video Tutorials | Learn JavaScript in 3 Hours | Must Watch it!

JavaScript Tutorial

Our JavaScript tutorial introduces the reader informally to the basic concepts and features of the JavaScript. We hope these JavaScript Tutorials are useful and will help you to get the best job in the industry. These JavaScript Tutorial are prepared by JavaScript Professionals based on MNC Company’s expectations. Stay tuned we will update New JavaScript Tutorials Frequently. If you want to learn Practical JavaScript Training then please go through this JavaScript Training in Chennai, JavaScript Training in Bangalore, and JavaScript Training in Pune.

Besant Technologies supports the students by providing JavaScript Tutorials for job placements and job purposes. JavaScript is the leading important course in the present situation because of more job openings and high salary pay. These are top JavaScript Tutorials, prepared by our institute experienced trainers.

These JavaScript tutorials are suitable for both freshers and experienced professionals at any level. These tutorials are for intermediate to somewhat advanced JavaScript professionals, but even if you are just a beginner or fresher you should be able to understand the tutorials by examples and explanations here we give.

JavaScript Introduction

If you’re wont to making structure, content, layout and elegance in your web content, isn’t it time to feature a bit behavior as well? of late, there’s no would like for the page to merely sit there. nice pages ought to be dynamic, interactive, and they should work together with your users in new ways in which. That’s wherever JavaScript comes in.

Let’s begin by taking a glance at however JavaScript fits into the online page ecosystem:

JavaScript is a programing language designed for web content, JavaScript enhances web content with dynamic and interactive options. it runs in the consumer software package.

JavaScript 1.3 works with version 4.0 browsers.

What will a JavaScript Do?

  • JavaScript offers hypertext mark-up language designers a programming tool.
  • JavaScript will respond to events.
  • Client-side validates.
  • It will find the visitor’s browser
  • Produce cookies.
  • Read/write/modify hypertext mark-up language elements JavaScript word.

JavaScript programming uses specialized terminology.

Understanding JavaScript terms is prime to understanding the script.

Objects, Methods, Properties, Functions, Events, Variables, Values, Operators, Expressions.

When a consumer makes the request, the hypertext mark-up language and every one script are downloaded into your browser and so the resultant hypertext mark-up language is displayed within the browser is termed client-side script.

JavaScript – Syntax

JavaScript is scripting language which can be implemented using <script>JavaScript Code </script> HTML tags in a web page.

You can write this tag <script> tags, which contains your JavaScript code, anywhere within your web page, but it is recommended to keep within the <head> tags.

While loading the web page browser identified JavaScript code inside the <script> tag.

Below is the simple syntax of JavaScript.

<script>
Your JavaScript code
</script>

The script tag contains two important attributes –

  • Language
  • Type

Language − This is required to specify which scripting language you are using and the value will be JavaScript.

Type − This required to indicate the scripting language which is getting used and needs to set using this attribute.

Below is the example of the above two attributes

<script language = "javascript" type = "text/javascript">
JavaScript code
</script>

Case Sensitivity

all the keywords, variables, function names, and any other identifiers must always be written in Proper case.

First Hello World JavaScript Program

<html>
<body>
<script language = "javascript" type = "text/javascript">
document.write("Hello World")
</script>
</body>
</html>

Semicolons are Optional – JavaScript can be written without semicolon if each Statement is placed in a separate line so it’s optional to write.

<script language = "javascript" type = "text/javascript">
var p1 = 10
var p2 = 20
</script>

Whitespace and Line Breaks – JavaScript ignores tabs, spaces, newlines that appear in JavaScript code. You can format your code to looks better and more readable.

Comments in JavaScript – Like other languages, JavaScript also supports comment which is useful for code understanding.

// This is single line comment in JavaScript
/* comment */  This multiple lines comments in JavaScript
<!--. JavaScript treats this HMTL comments as a single-line comment, just like // comment.
--> This HTML comment closing sequence not recognized by JavaScript so it should be written as //-->

Below is the example for the above comments

<script language = "javascript" type = "text/javascript">
<!-- HTML opening sequence
// Single line comment
/*
* This is a multi-line comment
*
*/
//--> HMTL closing sequence
</script>

Enabling Javascript In Browser

All the browser supports the JavaScript, to configure that we have to enable or disable manually. To enable the JavaScript in your browser, flow the below steps

To enable the JavaScript in Google Chrome:r

  • Step 1: Click on the menu at the top right corner in the chrome browser.
  • Step 2:  Select the settings.
  • Step 3: Click on show advanced settings at the end of the page.
  • Step 4:  open the Privacy section and then click on the Content settings button.
  • Step 5:  In JavaScript section select “Allow all sites to run JavaScript (recommended)” or “Do not allow any site to run JavaScript”.
  • Step 6:  Then close the settings window.

To enable the JavaScript in Internet Explorer

  • Step 1: Click on Tools Menu in the Internet Explorer or click on the gear icon.
  • Step 1: Select Internet Options from the Menu bar.
  • Step 2: Then Select Security Options from the dialog box.
  • Step 3: Click on the Custom Level button to proceed further.
  • Step 4: Scroll down the page until you find scripting options.
  • Step 5: Then Click on the Enable radio button under Active scripting.
  • Step 6: Finally click on the OK button to save the changes.

To enable the JavaScript in Opera

  • Step 1: Open the Opera browser.
  • Step 2: Click on the Opera icon at the top left of the window.
  • Step 3: Select the settings option from the menu list.
  • Step 4: Click on the website’s item on the left window.
  • Step 5: Under JavaScript heading, you will see two options “To enable JavaScript” and “To disable JavaScript”.
  • Step 6: To enable: Select the “Allow all sites to run JavaScript” (recommended).
  • Step 7: To disable: Select the “Do not allow any site to run JavaScript”.
  • Step 8: Once you selected your option, close the settings window and restart your Opera browser.

JavaScript (JS) – Placement in HTML File

JS Introduction

JavaScript is a scripting or programming language that allows implementing or making pages as dynamic. JavaScript can be used in different – different ways to achieve implementations.  The script should be contained or referred by an HTML document to be interpreted by the browser. It means that a web page can generate dynamic and programs also interact with the user so it will give more performance, required validation or calculation can be done at the client-side instead of sending of doing at service end.

Below are the things to be understood to place JS in HTML file

How to put a JavaScript code into an HTML page?

JavaScript code can put anywhere in an HTML document. Below are the preferred ways to implement JavaScript in an HTML file.

  • JS in <head>..JS..</head> section
  • JS in <body>..JS..</body> section
  • JS in <body>..JS..</body> and <head>…</head> sections
  • JS in an external file and this can include in <head>..JS File..</head> section.
JS in <head>..JS..</head> section

This will be used while working on some events. So this script will run when you click on an event, below is the example for the same.

<html>
<head>
<script type = "text/javascript">
function insideHead() {
alert("Hello World")
}
</script>
</head>

<body>
<input type = "button" onclick = "insideHead()" value = "ClickHere" />
</body>
</html>
JS in <body>..JS..</body> section

If you want to run the script while loading the page to generate content or other things then JS goes in the <body> part, below is the example for the same.

<html>
<head>
</head>

<body>
<script type = "text/javascript">
document.write("Hi JS placed inside body")
</script>
<h1>This is JS place in HTML understanding</h1>
</body>
</html>
JS in <body>..JS..</body> and <head>…</head> sections

You can put the above two together as well, below is the example for that.

<html>
<head>
<script type = "text/javascript">
function insideHead() {
alert("Hello World")
}
</script>
</head>

<body>
<script type = "text/javascript">
document.write("Hi JS placed inside body")
</script>
<input type = "button" onclick = "insideHead()" value = "ClickHere" />
</body>
</html>
JS in <body>..JS..</body> and <head>…</head> sections

You can include the JS file also to user-defined functions in file to HTML file. This will achieve code reusability. External JS file can include using the script tag and the src attribute below is the example for the same.

<html>
<head>
<script type = "text/javascript" src = "externalFile.js" ></script>
</head>

<body>
<h1>External JS example</h1>
</body>
</html>

Javascript Variables

Anything which can very is known as a variable. In the javascript phenomenon, it can have the data value with it and it is also changeable. But the type of the data which is holding by the variable is called as the data type in javascript. Will give a brief about the datatype which can be held by the variable

The compiler checks the type for its compatibility on all the operations whatever it is performing. So datatypes become very important attributes of an identifier which is common in every programming language. Which determines the values which are possible that the identifier could have and possible operations can be applied. The compiler can’t compile all the operations which have illegal operations.

In javascript, we have primitive data types and object data types. var is a keyword in javascript which used to declare the variable. you have an option to declare all the variables at once in javascript. also, you need not declare the variable datatype before you start using it. which means any values can be stored in any values. If you don’t define the variable using the var keyword, javascript will be automatically considered that the value is undefined. Number, String, Boolean, Symbol, Null, Undefined are the primitive data types in javascript and Array, JSON, function, object, and properties are the object datatypes.

Javascript can support number datatype and only one number datatype is present in it. It can store the floating-point, integer values.

String datatype supports the text data which should be within double or single quotes which starts from index 0 starting from the first character we mention in the text.

Boolean is a true or false type database which will be used to determine some condition is true or false.

Symbol datatype is another type that can identify a unique identifier.

Null datatype which says the datatype variable is an empty value.

Undefine datatype occurs when the data type variable is not declared with the var keyword.

Variable declaration and the initialization example:

Var one = 1;  //It stores numerical value
Var two = ‘two’  //it stores string value
Var three = 3.0  //it stores decimal value
Var four = true   //it stores Boolean value
Var five = null //it stores null value

It is not advised that without a var keyword we should not declare the variable which accidentally overwrites the existing global variable.

Javascript Operators

Operators are always playing a crucial role in a programming language. We perform any mathematical or any special operation in programming it helps to utilize.

JavaScript supports multiple operators like:

  • Arithmetic
  • Logical
  • Comparison
  • Assignment
  • Conditional

Here is some brief description about each operator:

Arithmetic Operator

It seems to perform mathematical operations like Addition, subtraction, multiplication, division, and module.

Example:

x+y , x-y,x*y, x/y,x%y

Logical Operator

It seems to check the logical condition, check whether the condition is true or false. Like &&(and),||(Or),!(Logical not)

Example:

x&&y ==0, x||y!=0

Comparison Operator

It supports the following comparison operators:

Like equal(==) ,not equal(!=), greater than (>),less than(<)

Example:

(x==y), x!=y, x>y, x<y

Assignment Operator

It is also known as, equal operator.

Like +=, -=,*=,/=,%= etc.

Example:

x+=y, x-=y, x*=y

Conditional Operator

Conditional operator(?:) : Conditional operator uses (?:) for true or false, it executes two or more statements.

Javascript if…else Statement

IF Else Statement always uses to make the decision of the program and handle all the correct actions.

JavaScript uses an if-else conditional statement which performs different actions.

If Statement:

It always uses to make decisions and execute statements conditionally.

Syntax:

If(condition)
{
//statement;
}

If else Statement

It is the next step of if statement, it allows JavaScript to control the condition.

Syntax:

If(condition)
{
//Statement
}
else
{
//Statement
}

If Else If statement:

It allows JavaScript to make the correct decision out of several conditions.

Syntax:

If (expresson 1)
{
//Statements
}
Else if
{
//Statements
}
Else
{
//Statements
}

Javascript Switch Case

Switch case is always been used to execute expression or condition along with variable specifications.

Switch case is converting the specific data into cases:

For instance:

Switch(Condition/Expression)

{
Case 1:
//Provide statement;
Case 2:
//Provide statement;
Case 3:
//Provide statement;
Default:
//Statement
}

Rather it gets the case, however, it does not find the case-control move on to default it will always be true except all the cases.

Example:

<script type=”text/javascript”>
var class=’First’;
switch(class)
{
Case ‘First’:document.write(“First class”);
Break;
Case ‘Second’:document.write(“Second class”);
Break;
Case ‘Third’:document.write(“Third class”);
Break;
Default: document.write(“unknown class”);
}
</script>

 Javascript While Loops

For loop is the most import concept in each and every programming language. It always contains loop initialization, test statement, iteration statement.

For loop is been used to initialize or traversing the data along with a condition. Either defined increment or decrement operator at the end of conditions…

Example:

Var a;
For(a=0; a<10; a++)
{
Document.write(a);
}

Syntax:

For(initialization; test statement; iteration)

Example:

For(i=0; i<=10; i++)
Program of For Loop:
<script type=”text/javascript”>
var couter=0;
for(counter=0; counter<=10; counter++)
{
Document.write(“Current count:”+counter);
}
</script>

Javascript For Loop

While the loop is always executed the statement or code repeatedly. It always returns true if a condition is true. Instead of If statement, We can get enhance if, which is called while loop. It never works without condition or expression. Providing some condition it will easily work to get the proper outcome.

Example 1:

Var counter=0;
While(Counter<10)
{
Document.write(Counter);
Counter++;
}

Syntax:

While(expression)
{
//statement()
}

Example 2:

<script type=”text/javascript”>
var counter=0;
while(counter<10)
{
Document.write(“Current Count:”+counter+”<br/>”);
}
</script>

Javascript for…in loop

For..in is used to loop over the properties of an object. The set of code inside the loop will be executed for each property of an object.

Syntax:

For(variable in Object)
{
//code here
}

Example 1:

var address = {city:"Chennai", state:"Tamil nadu", country:"India"};
var text = "";
var x;
for (x in address) {
text += address[x] + "<br>";
}
Console.log(text);

Output:

Chennai

Tamil Nadu

India

We can’t use the for..in statement to loop array values but index order is important. The below example demonstrates the reason for that.

Click Here-> Are you Interested in JavaScript?

Example 2:

var arraylist = [];
arraylist [5] = "Hello";
console.log("for...of:");
var count = 0;
for (var item of arraylist) {
console.log(count + ":", item);
count++;
}
console.log("for...in:");
count = 0;
for (var item in arraylist) {
console.log(count + ":", item);
count++;
}

Output

for…of:

0: undefined

1: undefined

2: undefined

3: undefined

4: undefined

5: Hello

for…in:

0: 5

For..of loop properly worked on with index value. But for..in.can’t do that.

JavaScript loop control

Loop control statements deviates a loop from its normal flow. All the loop control statements are attached to some condition inside the loop. We can achieve that in two ways.

They are:

  1. Break statement
  2. Continue statement

Break statement

The break statement is used to break the loop in some conditions.

For Statement

Syntax:

For(initialization;condition;Increment/decrement)
{
If(condition)
{
Break;
}
Statements;
}

While Statement

Syntax:

Initialization;
While(condition)
{
If(condition)
{
Break;
}
Statements;
Increment/decrement;
}

Example:

<script>
for(var i=0;i<20;i++)
{
if(i==5)
{
break;
}
console.log(i);
document.write(i+"<br>");
}
</script>

Output:

0

1

2

3

4

The loop should print from 1-20. But inside the loop, we have given a condition that if the value of  I equals 5, then break out of the loop. It will break the loop when it reaches 5.

Continue statement

It is used to skip an iteration of a loop.

For Statement

Syntax:

For(initialization;condition;Increment/decrement)
{
If(condition)
{
Continue;
}
Statements;
}

While Statement

Syntax:

Initialization;
While(condition)
{
If(condition)
{
Continue;
}
Statements;
Increment/decrement;
}

Example:

for(var i=0;i<10;i++)
{
if(i%2==0)
{
continue;
}
console.log(i);
document.write(i+"<br>");
}

Output:

1
3
5
7
9

In the above code when I value becomes an even number, continue forces the loop to skip without further executing any instructions inside the loop in that current iteration.

Javascript labels using loop control

The break statement, without a label reference used to escape from loop or switch statement. With label reference, it can jump out any code block.

Syntax:

Label:

Statement;

For break

Break Label;

For continue

Continue Label;

Example:

var fruitlist = ["apple", "orange", "grapes", "banana"];
var text = "";
list: {
text += fruitlist[0] + "<br>";
text += fruitlist[1] + "<br>";
break list;
text += fruitlist[2] + "<br>";
text += fruitlist[3] + "<br>";
}
document.write(text+"<br>");

Output:

apple

orange

A code block is a block of code between { and }.

Javascript Functions

A Function is a set of instruction or code that is used to perform a particular task. It is will execute the code when it is called or invoked.

There are two types of Functions:

  • Predefined functions
  • User-defined functions
Predefined functions

It is a build-in function in javascript that is readily available for use.

Example 1:

  • Math.sin(x) – It is used to find the sin value of x.
  • Math.Sqrt(x) – It is used to returns the square root of a number.
  • Math .pow(x,y) – It is used to find the power value x of y.

Example 2:

document.write(“Square root of 25 is: “+Math.sqrt(25)+”<br>”);

document.write(“Power of 5 of 3 is: “+Math.pow(5,3));

Output:

square root of 25 is: 5

Power of 5 of 3 is: 125

User-defined functions

There are three stages for functions:

  • Function declaration
  • Function definition
  • Function call or invoke

Syntax

Function function name(Parameter1,Parameter2 …)

{
//Set of code here
}

Function Types

There are three types of function is available in javascript. They are:

  • Named function
  • Anonymous function
  • Immediately invoked function
Named function

Named functions that are defined in code with the name. We can call or invoke that function using that name.

Example:

//Function definition
function welcome()
{
document.write("Welcome to Javascript");
}
welcome();//Function calling

Output:

Welcome to Javascript

Function with parameter

Parameters are used when defining a function. It may have any number of parameters. Whereas in arguments are he values the function receives from each parameter when the function is called or invoked.

function addition(num1,num2)//this is parameter
{
document.write("Addition value is: "+(num1+num2));
}
addition(45,67);//Here it is called as arguments

Output:

Addition value is: 112

Function with return type

Every function is javascript will return undefined unless it specified. We can return any value from function through return keyword.

Example:

function square(num)
{
return num*num;
}
document.write("Square value is: "+square(25));

Output:

Square value is: 625

Anonymous function

It is one of the functions without a name. We can call the function with a variable name.

Example:

var square= function (num)
{
return num*num;
}
document.write("Square value is: "+square(25));
Immediately invoked function immediately invoked function>

It is immediately invoked by the browser as soon as found. It is automatically invoked by the browser without any call.

Example:

(function()
{
document.write("This is Immediate called function.");
})();

Output

This is Immediate called function.

Javascript events

Events are states of change on HTML controls. We can execute the javascript code when something changes occurred in HTML controls occurs. It may do by the user or browser.

Example of Events

  • HTML page finished loading
  • When clicking on the button
  • When mousing over the content or HTML Controls.

When particular events occur we can execute the javascript code.HTML event handler attributes available for HTML tags

Syntax:

<tagname event=”JS  call”>

Example:

<input type=”button” onclick=”Welcome();”>

When the button is clicked, It will call the javascript welcome function.

Common events

  • On click – It will fire when click event happens.
  • On submit – It will fire when submit event happen
  • On MouseOver- When over the content
  • Onload – When HTML page finished the loading
  • onmouseout – When mouse out the controls.
  • On change – when the input value was changed.
  • On keydown – when Keyboard key pressed

Example:

<html>
<body>
<script type = "text/javascript">
function addition(num1,num2)//this is parameter
{
document.write("Addition value is: "+(num1+num2));
}
</script>
<input type="button" onclick="addition(56,78);" value="Addition">
</body>
</html>

Output:

When clicking the Addition button it will show:

Addition value is: 134

Javascript and Cookies

Cookies are a small amount of data or plain text files that are stored in a browser.  A cookie is useful information on the web page.

  • Create the cookie
  • Read the stored cookie value
  • Modify the cookie value
  • Delete the cookie

Cookies are stored in a name-value pair.

Username=”David”

Create the cookie:

Javascript cookies are created by document.cookie property.

document.cookie =” fname =David”
document.cookie =” lname =Selandar”

Read the stored cookie value

We  Can get all storied value in cookie of the browser as:

document.cookie

It will how all cookie value as name-value pair.  Output will be

fname= David; lname= Selandar

Modify the cookie value

We can modify the cookie value same way as create like:

document.cookie =” fname =Martin”

document.cookie =” lname =Walton”

Delete the cookie

We can delete the cookie through value as empty and expiry date as a past value

document.cookie = ” fname =; expires=Wed, 01 Jan 1940 00:00:00 UTC; path=/;”;

Page Redirection

There square measure a few of the ways to direct to a different webpage with JavaScript.

  • If the domain owner not interested in the name then change to a new name. In such a situation, the owner might be want to direct all guests to the new domain. Here you’ll be able to maintain your recent domain however place one-page domain with a page domain redirection specified all of your recent domain guests can return to your new domain.
  • If domain owners create multiple pages depends on the versions of browsers based on the various countries, then replace using page redirection use client-side page domain redirection to land site users on a suitable page.
  • The page which is used for search is already indexed. But whereas moving to a different domain, the owner wouldn’t feel to lose your guests by through coming search engines. So the owner can use client-side page domain redirection. but detain mind this could not be done make fool the programmer, it may lead your website to urge illegal.

JavaScript URL Redirection

you can use several ways to airt an online page to a different one. Almost all methods are related to the window. Placed object, is an attribute of the Window object. It is often accustomed get this URL address (web address) and to airt the browser to a replacement page.

.href = "https://www.besanttechnologies.com/";
.replace("https://www.besanttechnologies.com/");

Example 1:

<html>
<head>
<script type = "text/javascript">
<!--
function Redirect() {
window.location = "https://www.besanttechnologies.com";
}         //-->
</script>
</head>

<body>
<p>Click the following button, you will be redirected to home page.</p>
<form>
<input type = "button" value = "Redirect Me" onclick = "Redirect();" />
</form>
</body>
</html>

Example 2:

The following example shows how to redirect your site with setTimeout() function

<html>
<head>
<scripttype="text/javascript">
<!--functionRedirect()
{window.location="https://www.besanttechnologies.com";}
document.write("You will be redirected to main page in 10 sec.");
setTimeout('Redirect()',10000);//-->
</script>
</head> 
<body>
</body>
</html>

Example 3:

The following example shows how to redirect your site visitors onto a different page based on their browsers.

<html>
<head>
<scripttype="text/javascript">
<!--varbrowsername=navigator.appName;
if(browsername=="Netscape")
{window.location="http://www.location.com/ns.htm";}
elseif(browsername=="Microsoft Internet Explorer")
{window.location="http://www.location.com/ie.htm";}
else
{window.location="http://www.location.com/other.htm";}//-->
</script>
</head>
<body>
</body>
</html>

Dialogue Boxes

These boxes are often accustomed to alert and raise or to urge confirmation on any predefined input or to user-defined input. this is going to discuss every panel one by one.

Alert Box

It is used on the website to show the message of warning to the user that they have wrongly entered the value other than else what is required to fill that place. an alert box can still be used as a user-friendly message. Alert box provides just one button “OK” to pick out and proceed.

Example :

<html>
<head>
<script type = "text/javascript">
function Warn() {
alert ("welocmebesant technologies");
document.write ("This is a warning message!");
}
</script>
</head>
<body>
<p>Click the following button to see the result: </p>
<form>
<input type = "button" value = "Click Me" onclick = "Warn();" />
</form></body></html>

Output:

Alert Box

Alert Box Output

Confirmation Dialog Box

A make sure box is commonly used if the user wishes to verify or settle for one thing. When a make sure pop up of box, the user can have to be compelled to confirm either “OK” or “Cancel” to move further.  the user confirms on the OK button, the window functionality confirms ()  return true. if the user confirms on the Cancel button, then it will return false and it shows null.

<html>
<head>
<script type = "text/javascript">
<!--
functiongetConfirmation() {
varretVal = confirm("Do you want to continue ?");
if(retVal == true ) {
document.write ("stubdent  wants to continue!");
return true;
               } else {
document.write ("stubdent does not want to continue!");
return false;
               }
            }
         //-->
</script>
</head>
<body>
<p>Click the following button to see the result: </p>
<form>
<input type = "button" value = "Click Me" onclick = "getConfirmation();" />
</form>
</body>
</html>

Output:

Confirmation Box

Prompt Dialog Box

A prompter’s box is usually used if you would like the user to want to input a worth before getting into a page. When prompters pop up the box, the user can confirm either “OK” or “Cancel” to proceed when getting into Associate in Nursing input worth. If the user confirms the OK button, the window method will return the entered data from the text box. If the user confirms the Cancel button, the window method will return null.

Example:

<html>
<head>
<script type = "text/javascript">
<!--
functiongetValue() {
varretVal = prompt("Enter your name : ", "your name here");
document.write("You have entered : " + retVal);
}
//-->
</script>
</head>
<body>
<p>Click the following button to see the result: </p>
<form>
<input type = "button" value = "Click Me" onclick = "getValue();" />
</form>
</body>
</html>

Output:

Prompt Dialog Box

Void Keyword

The voids is a vital keyword in JavaScript which might be used as a single operator that seems before its single quantity, which can be of any sort. This operator specifies associate degree expression to be evaluated while not returning a price.

Syntax:

The syntax of the void can be either of the following two −

<head>
<script type = "text/javascript">
<!--voidfunc()javascript:voidfunc()or:void(func())javascript:void(func())      //-->
</script>
</head>

Example 1:

Here the expression alert (‘Warning!!!’) is evaluated but it is not loaded back into the current document −

<html>
<head>
<scripttype="text/javascript"><!--//-->
</script>
</head>
<body>
<p>
Click the following, This won't react at all...
</p>
<ahref="javascript:void(alert('Warning!!!'))">Click me!
</a>
</body>
</html>

Output:

Example :

<html>
<head>
<scripttype="text/javascript"><!--//-->
</script>
</head> 

<body>
<p>Click the following, This won't react at all...</p>
<ahref="javascript:void(0)">Click me!</a>
</body>
</html>

Example :

<html>
<head>
<scripttype="text/javascript">
<!--functiongetValue(){vara,b,c;   a =void( b=5, c =7);
document.write('a = '+ a +' b = '+ b +' c = '+ c );}//-->
</script>
</head> 

<body>
<p>Click the following to see the result:</p>
<form>
<inputtype="button"value="Click Me"onclick="getValue();"/>
</form>
</body> 
</html>

Output:

void keyword output

 

Page Printing

Page print in JavaScript may be a straightforward code in JavaScript wont to print the content of the net pages.

  • The print() is the output method, it is used to print the data one the current window.
  • It basically opens the Print output dialog box which is used to let you select the between different printing options.

Syntax:

window.print()

Parameters – No parameters required

Returns – This function do not return anything

Example :

<!DOCTYPE html>
<html>
<head>                                   
<script type="text/javascript">            
</script>            
</head>            
<body>                        
<h2>HI Besant Technologies USER'S</h2>           
<form>                      
<input type="button" value="Print" onclick="window.print()" />          
</form>          
</body>
<html>

Output:

page printing output

 

Page Printing

Objects Overview

It is an OOP based programming language. A programing language is known as object-oriented, it is having  four basic capabilities to developers

  • Encapsulation: Is a mechanism to bind methods and data in one unit.
  • Aggregation: Having strong relations in between objects.
  • Inheritance: Reusing the old properties for the new class.
  • Polymorphism: Single functions multiple developments.

Object Properties

Any of the abstract information sorts, like another object. Object properties area unit sometimes variables that area unit used internally within the object’s strategies, however, may also be globally visible variables that area unit used throughout the page.

syntax:

objectName.objectProperty = propertyValue;

Example:

varstr = document.title;

Object Methods

There is a little distinction between an operate ANd away – at a operate may be a predefined unit of statements and away is hooked up to it and can be called by the keyword is this.

Methods area unit helpful for all from displaying the data of the thing to the screen to playing complicated mathematical functionalities on a bunch of native parameters and properties.

Example:

Following may be an easy example to indicate the way to use the method write () of the document object to write down any data on the document.

documentcustom.write("This is test");
Non-Pre-Defined Objects

All non-pre-defined objects and in-built objects are descendants to an object known as Object.

New Operator

It is employed to make an object is an instance. To do an object, it is followed by the builder technique.

In the following illustration of an example, the builder strategies are Date(),Array(), and Object().

It is inbuilt JavaScript functions.

var newemployee =new_Object();
var newbooks =new_Array(,"Java","Perl","C++",);
var newday =new_Date("January 20, 1947");

The Constructor of an Object()

A builder may be a perform that makes Associate of an object initializes. it gives a special builder perform referred to as Object() to make the item. The come back price to an Object() builder is appointed to the variable.

Try the following example; it demonstrates how to create an Object.

Example 1:

<html>
<head>
<title>
User-defined objects
</title>
<scripttype="text/javascript">
var book =newObject();
// Create the objectbook.subject="Technologies";
// Assign properties to the objectbook.author="Besant";
</script>
</head> 
<body>
<scripttype="text/javascript">
document.write("Book name is : "+book.subject+"<br>");
document.write("Book author is : "+book.author+"<br>");</script>
</body>
</html>

Output:

Book name is: Technologis Book author is: Besant

Example 2:

This example demonstrates how to create an object with a User-Defined Function. Here this keyword is used to refer to the object that has been passed to a function.

<html>
<head>
<title>User-defined objects</title>
<scripttype="text/javascript">
function book(title, author)
{this.title= title;this.author= author;}
</script>
</head> 
<body>
<scripttype="text/javascript">
varmyBook=new book("Technology","Besant");
document.write("Book title is : "+myBook.title+"<br>");
document.write("Book author is : "+myBook.author+"<br>");
</script>
</body>
</html>

Output:

Book title is: TechnologyBook author is: Besant

Defining Methods for an Object

The previous examples demonstrate however the creator creates the item and assigns properties. But we want to complete the definition of Associate in a Nursing object by distribution ways thereto.

Example:

Try the following example; it shows how to add a function along with an object.

<html>
<head>
<title>User-defined objects</title>
<scripttype="text/javascript">
// Define a function which will work as a methodfunctionaddPrice(amount)
{this.price= amount;}
function book(title, author)
{this.title= title;this.author= author;this.addPrice=addPrice;
// Assign that method as property.}
</script>
</head> 

<body>
<scripttype="text/javascript">
varmyBook=new book("Technologies","Besant");
myBook.addPrice(100); 
document.write("Book title is : "+myBook.title+"<br>");
document.write("Book author is : "+myBook.author+"<br>");
document.write("Book price is : "+myBook.price+"<br>");
</script>
</body>
</html>

Output

Book title is: Technologies

Book author is: Besant

Book price is: 100

JavaScript Native Objects

It has several in-built or native objects. This objects area unit accessible anyplace in your code and can work an equivalent approach in a browser running in any software system.

Javascript The Number Object

The Number object states the numerical date, i.e. integers or floating numbers. We don’t have to care about Number objects because of the browser is internally responsible for the conversion between number literals to instances of number class.

Syntax:

var testVar = new Number(number);

here, the number should be a numerical value, if any non-numerical argument, then it can not be converted into a number, and it returns Not-a-Number(NaN).

Properties of Number

1. MAX_VALUE The maximum possible value of a number 1.7976931348623157E+308

2. MIN_VALUE The minimum possible value of a number 5E-324

3. NaN Not a number

4. NEGATIVE_INFINITY Less than MIN_VALUE

5. POSITIVE_INFINITY Greater than MAX_VALUE

6. prototype Prototype is the static Number object property, The usage of Prototype to assign new properties as well as methods to Number object in the current document.

7. constructor Default this is the Number object. It will return the function that created this object’s instance.

Number Methods

isFinite(): To check the value is the finite number or not.

isInteger(): To check value is the integer or not.

parseFloat(): To make the conversion of the given string into the floating-point number.

parseInt(): To make the conversion of the given string into an integer number.

exponential(): Returns exponential notation of the number.

toFixed(): Fixed a number with a specific number of digits after the decimal of the number.

toPrecision(): By using this we can define total number digits including digits from both ends left and right of the decimal to display.

toString(): Returns a string representation of the given number.

Javascript The Boolean Object

The Boolean object has 2 values only i.e. “true” or “false”. If argument left blank or have undefined Empty string “”, or like these values, so initially object will have false value.

Syntax:

var testVar = new Boolean(value);

Properties of Boolean

1. prototype Prototype to assign new properties as well as methods to a Boolean object.

2. constructor Returns reference of Boolean function that created a Boolean object.

Boolean Methods

toSource(): Provide the calling source of the Boolean object as in the string.

toString(): Use to convert a Boolean object into String.

valueOf(): Returns the primitive value of the Boolean object.

Javascript The String Object

The String object helps to store more than one character in the single variable as the series of characters.

Syntax:
var testVar = new String(string);

Properties of String

1. prototype Prototype to assign new properties as well as methods to an object.
2. constructor Returns reference of String function that created an object.
3. length Gives the length of the string.

String Methods

charAt(): To get an index.

charCodeAt() To get the Unicode value of a character.

concat(): Combine two or more strings.

indexOf(): Helps to find the position of a character value in the given string.

LastIndexOf(): Search from the last of the string and give an index of it.

search(): Helps to search within the string and give an index of it.

match(): Search for the expression in the string and give that as an output.

replace(): Helps to replace some part of the string at a particular index.

substr(): To get the part of the string using an index value and length of the string.

substring(): Get part of the string based on an index.

slice(): Get part of the string based on +ve as well as -ve index of the string.

toLowerCase(): To change the string from upper case to lowercase. 13.toLocaleLowerCase() To change the string

from upper case to lowercase based on the host system.

uppercase(): To change the string from lower case to uppercase

toLocaleUpperCase(): To change the string from lower case to uppercase based on the host system.

toString(): Helps to get the string refers to the object.

valueOf(): Give the primitive value of the string.

Javascript The Array Object

The Array object can store more than one value (which should same in data type) in a single variable. The array is fixed-size collection of values, it used to store a collection of data.

Syntax:

var testVar = new Array(“value1”, “value2”, “value3”);

Example:

var human = [ “hair”, “nose”, “face”];

Properties of Array

1. prototype Prototype to assign new properties as well as methods to an object.
2. constructor Returns reference of Array function that created an Array object.
3. index Represents index which is starts with 0.
4. input For regular expression matches.
5. length Number of elements in the Array.

Array Methods

Concat(): Combine two or more arrays into the new array.

copywriting(): Copy the array itself for the given elements.

every(): To checks if all the elements of the particular array have validated conditions as per the function or not which is provided to it.

fill(): Helps to fill elements to a new array.

filter(): Filter the array based on the passing arguments.

find(): Helps to find the element based on a condition specified to it.

findIndex(): Return the index of the element.

forEach(): Loop through the elements of an array one by one.

includes(): To find a particular element is represented in an array or not. 10.indexOf() Helps to search the array for specific elements and return the index of it in the first match.

join(): Combine the elements of the array and returns the string. 12.lastIndexOf() Same as indexOf() but starts from the last element of the array.

map(): Helps to call the function for elements and give the new array.

pop(): Delete the last element of the array.

push() Add element or elements at the last element of the array.

reverse(): Reverse the array elements.

shift(): It delete and give the first element.

slice(): Based on the index it cuts the array into a new array. 19.sort() Helps to sort the array into specific sorting.

splice(): It helps in adding or removing the elements from the array.

unshift(): To add elements at the starting of the array.

Javascript The Date Object

Date Objects:

The Date object helps to get a day, month and year. We can use different constructors to create Date object, as shown in the syntax below.

Syntax:

new Date( ) new Date(milliseconds)
new Date(datestring)
new Date(year,month,date[,hour,minute,second,millisecond ])

Properties of Date

1. prototype Prototype to assign new properties as well as methods to an object.
2. constructor Returns reference of function that created an object.

Date Methods

getDate(): Gives the date between 1 and 31.

getDay(): Gives Day value between 0 and 6.

getFullYears(): Gives the Year value.

getHours(): Gives the value between 0 and 23.

getMilliseconds(): Gives the integer value between 0 and 999.

getMinutes(): Gives the integer value between 0 and 59.

getMonth(): Gives the integer value between 0 and 11.

getSeconds(): Gives the integer value between 0 and 60.

getUTCDate(): Gives the integer value between 1 and 31 based on universal time.

getUTCDay(): Gives the integer value between 0 and 6 on universal time.

GetUTCFullYears(): Gives the integer value of the year based on universal time.

getUTCHours(): Gives the integer value between 0 and 23 based on universal time.

getUTCMinutes(): Gives the integer value between 0 and 59 based on universal time.

getUTCMonth(): Gives the integer value between 0 and 11 based on universal time.

getUTCSeconds(): Gives the integer value between 0 and 60 based on universal time.

setDate(): Sets day for the specific date based on the local time.

setDay(): Sets weekday based on local time.

setFullYears(): Sets the year value for the specified date based on local time.

setHours(): Sets the hour value for the specified date based on local time.

setMilliseconds(): Sets the milliseconds value for the specified date based on local time.

setMinutes(): Sets the minutes value for the specified date based on local time.

setMonth(): Sets the month value for the specified date based on local time.

setSeconds(): Sets the seconds value for the specified date based on local time.

setUTCDate(): Sets the day value for the specified date based on universal time.

setUTCDay(): Sets the day of the week based on universal time.

setUTCFullYears(): Sets the year for the specified date based on universal time.

setUTCHours(): Sets the hour for the specified date based on universal time.

setUTCMilliseconds(): Sets the milliseconds for the specified date based on universal time.

setUTCMinutes(): Sets the minutes for the specified date based on universal time.

setUTCMonth(): Sets the month for the specified date based on universal time.

setUTCSeconds(): Sets the seconds for the specified date based on universal time.

toDateString(): Gives the date part of a Date object.

ToISOString(): Gives the date in ISO format string.

toJSON(): Gives the Date object for JSON serialization.

toString(): Convert a date into the string.

toTimeString(): Gives the time part of a Date object.

toUTCString(): Converts date in the form of the string by UTC time zone.

valueOf(): Gives the primitive value of the Date object.

JavaScript Math Object

Allows you to perform mathematical tasks on numbers. It supports numbers, fractions, units, strings, constants.

Does symbolic computation. (i.e: Symbol(Symbol.toStringTag): “Math”)

Available in both Command Line Interface(CLI) & User Interface (UI) with a large set of built-in functions and constants. And also runs in all kind of JavaScript engine

All properties and methods of Math are static(i.e: can’t modify).

“Math” is an Object available with “window” object in browser and in with “global” object in CL.

In the following sections, we will have a few examples to demonstrate the usage of the methods associated with Math.

Constants

Examples:

Euler’s constant (e)

Math.E; // 2.71828

Natural logarithm of 2

Math.LN2; // 0.69314

Math.LOG2E

Math.LOG2E; // 1.44269

Ratio of the circumference of a circle to its diameter

Math.PI; // 3.14159

Methods

Examples:

Numerical Functions

Returns the absolute value of x.

Math.abs(‘-1’); // 1

Math.abs(5.999);  // 5.99

Returns the value of x to the power of y

Math.pow(8, 2); // returns 64

Returns the smallest integer greater than or equal to a number

Math.ceil(.95); // 1

Math.ceil(7.004); // 8

Math.ceil(-0.95); // -0

Returns x rounded to the nearest integer

Math.round( 70.49); //  70

Math.round( 80.5);  //  81

ath.round(-30.5);  // -30

Trigonometric functions (Return angles as radiants)

Math.acos(-2);  // NaN

Math.acos(-1);  // 3.141592653589793

Math.acos(0);   // 1.570796326794896

To convert radians to degrees, divide by (Math.PI / 180) * Math.asin(0.5); // 0.009138522593601258

Note: The Math.asin() method returns a numeric value between – π/2  and  π/2  radians for x between -1 and 1.

Regular Expression

A regular expression is a string, which is the combination (or) sequence of characters. It is widely used as a search pattern on strings operations like; find, find & replace. In modern browsers, Javascript provides a standard constructor function “RegExp” to support regular expression.

Syntax:

x = new RegExp(<string>, <options>) - Constructor representation
y = /<string>/<options> - Literal representation

Note: For the same input, both x & y will give the same regular expression.

Available options:

g – Uses for global search

i – Uses for case-insensitive search

m – Uses for multiline search

Example 1: /Regular Expression/gi.test(<string>)
Example 2: /[xyz]/ (or) /[0-9]/ (or) /[a-zA-Z]/     
Search any one character from the string
Example 3: /[^xyz]/ (or) /[^0-9]/ (or) /[^a-zA-Z]/
Search any one character from the string that is not present inside the brackets
Example 4: /[p|q]/     
Search any alternate character from the string
Example 5: /\s/
Search for a space in the string and returns the 1st match
Example 6: /\w+/            
Search for multiple words in the string and returns those in an array
Search Includes (_, 0-9, A-Z, a-a )
Example 7: /^.{4}$/
Search for string that contains only 4 characters.

Methods:

test() – search the pattern for a match in the string and return true if the pattern found or else returns false.

exec() – search the pattern for a match in the string and return the first search value.

 Javascript Document Object Model

DOM – Document Object Model; Represents an element Object tree

DOM is nothing but an Object or a platform that provides access to update the content & structure and view(i.e: style)of the document. There are 3 types of DOM available. And those are:

  • Core DOM – Standard Object representation for all types of DOM. (i.e: Base for other DOM)
  • XML DOM – Standard Object representation for all types of XML Document
  •  HTML DOM – Standard Object representation for all types of HTML Document

XML DOM & HTML DOM are the standard Object representation/Model and Interface for XML & HTML.

When a document loads into browser then browser parses the XML/HTML program and converts the elements into Objects.

The attributes of each element will act as a property in that Object. And the events will bind to the Objects so that directly developer can execute those methods. After parsing the whole DOM, each and every wrapper elements formed as NodeList and added into HTMLNodeList. As the HTMLNodeList connected to Javascript so it is for the developer to perform some action like element addition, element removal, element update, attribute update, style change.

Javascript Errors & Exceptions Handling

You will get Errors in Javascript maybe because of our mistakes, and unexpected user input, erroneous server response and etc. Usually, the current execution block of the script will die (stops the execution) in case of any error and prints in the console.

Type Of Errors

Below are the Errors present in Javascript.

  • EvalError : The error has occurred in the eval() function.
  • RangeError: A numbers are “out of range” has occurred
  • ReferenceError: Because of an illegal reference
  • SyntaxError: Occurred when a statement violates the syntax of the language
  • TypeError: Occurred when incompatible types are operating together. (i.e: 1..toUpperCase())
  • URIError : Occurred when encodeURI() has problems

Apart from this, you can create a custom error with a message. Ex: throw new Error(‘My Custom Message’)

How to handle these errors?

try..catch that allows to “catch” errors and, handles that error scenario by doing some reasonable like logging info or routing to some different view.

Syntax:

try {
// Block of code to try
}
catch(err) {
//Block of code to handle errors
}
finally {
// Block of code to be executed regardless of the try / catch result
}

How does it work?

  • First the code in try{…} block will execute.
  • If there is any error occurred then the control of execution goes to catch(err){…} block leaving the try{…} block scope.
  • The “err” variable in the “catch” block will be holding all the information related to the error occurred in the “try” block.
  • Atlast irrespective of any success or failure or error scenarios finally{…} block will execute. This is for clean up activity.

Example 1:

const x = 5
try {
console.log(y) // y is not defined, so throws an error i.e: ReferenceError
} catch (error) {
console.error(error) // will log the error with the error stack
} finally {
console.log(x) // will always get executed
}

Example 2:

Promise.resolve("Success Response")
.then(res => {
console.log(res) // Success Response
throw new Error('something went wrong')
})
.catch(err => {
console.error(err) 
// we will see the error message (i.e: something went wrong) here.
resolvedFunction("resolved value at error handler") 
// we handled the error and we decided to resolve the error with some value
})

Form validation in Javascript

We can validate our client-side forms logic with Javascript Form Validation and it prevents sending malicious/unaccepted data to server from client. If any web page accepts user information/inputs, then that information needs to be checked because maybe the data entered is inappropriate for our server. If the web page handles client-side validation for user inputs then the data processing will be faster in the server.

Form Validation includes 2 types of functions. i.e: Basic Form validation & Form Data validation

  • Basic Form Validation: All the required fields need to be filled.
  • Form Data validation: Entered data should be appropriate as per acception

Example:

<html>
<body>
<header></header>
<main>
<form name="formForValidation" onsubmit="return validate();">
<table>
<tr>
<td>Full Name: </td>
<td>
<input name="name" type="text" />
</td>
</tr>
<tr>
<td>Username: </td>
<td>
<input type="text" name="username" />
</td>
</tr>
<tr>
<td>Email: </td>
<td>
<input type="text" name="email" />
</td>
</tr>
<tr>
<td>Password: </td>
<td>
<input type="password" name="password" />
</td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value="Submit" />
</td>
</tr>
</table>
</form>
</main>
<footer>
<script>
function validate() {
let isValidated = true;
// Basic Form Validation
document.querySelectorAll('input[name]').forEach(node => {
if (!node.value) {
isValidated = false;
});
/*** Form Data Validation
* 1. check valid email id
* 2. check valid alphanumeric password with minlength = 8
*/const emailRegEx = /^(([^<>()[\]\\.,;:\s@\"]+
(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+
[a-zA-Z]{2,}))$/;
const email = document.formForValidation.email.value;
if (!(email && emailRegEx.test(email))) {
isValidated = false;
}
const alphanumeric = /^([a-zA-Z0-9 _-]+)$/;
const password = document.formForValidation.password.value;
if (!(password && alphanumeric.test(password) && password.length > 7)) {
isValidated = false;
}
console.log(`Form Validation: ${isValidated}`);
return isValidated;
}
</script>
</footer>
</body>
</html>

Animation in Javascript

Animation means to do something that makes it happens to move. something like text or images in the browser.

  • Can you make animation in javascript by using three important functions like setTimeout(), setInterval(),clearTimeout().
  • In javascript make animations with DOM elements. Using DOM element move from right to left like this.
  • You can make it a DOM object using a position on the screen.

Type of Animation in Javascript

Manual Animation

Using the DOM object get the value of the element of the HTML tag in the page by using the getdocumentElementByID() method.

Automated Animation

Using setTimeout(),setInterval(),ClearTimeout() using those functions do the automated animation.

Animation in Javascript

  • SetTimeout(function, duration)

This function calls the function after duration milliseconds now.

  • SetInterval(function,duration)

This function call the function after every duration milliseconds.

  • clearTimeout(settimeout variable)

This function clears any timer set by settimeout function.

Animation in Javascript

To set any object in the screen as following syntax

object.style.left = distance in pixels or points.

Example:

object.style.left = “20px”;

object .style.top = “20px”;

Manual Animation

Manual Testing

OutPut:

file:///F:/javascript-animation/manual-animation.html

Manual Testing Output

Automatic Automation

Automatic Animation

OutPut:

file:///F:/javascript-animation/auto-animation.html

Automatic Animation Output

Mouse Operation

Mouse Operation

Output:

file:///F:/javascript-animation/mouse-animation.html

Mouse Operation Output

Java Script Multimedia

The JavaScript navigator object incorporates a scamp object called plugins. This object is an exhibit, with one passage for each module introduced on the browser.

The plugins are supported by Firefox, Mozilla, and Netscape only

JavaScript multimedia can be used to include any movies and music etc., You can playback control for any video players.Using <video> tag to include video in HTML pages. Multimedia in javascript having navigator object includes child object is called plug-ins. Using plug-ins to include multimedia in HTML pages like  Adobe Flash Player. Using the above plug-ins you can play any video files or audio files.

Here list some plugins installed in your browser

Javascript Multimedia

Multimedia Table

Checking for Plug-Ins and Controlling Multimedia

Every entry having the following types of possessions

  • Name
  • File Name
  • Description
  • Mime type

Multimedia supports video or audio formats. Video formats like MPEG, AVI, WMV, Flash, MP4. Audio formats like MP3, MP4, WMA, WAV. You can add video or audio using plug-ins.

<video src=“rabbit320.webm” controls>
</video>

plugins cheacking and controlling multimedia
Output:

Multimedia Output

Debugging in JavaScript

An oversight in a program or a content is alluded to as a bug. The way toward finding and fixing bugs is called troubleshooting and is a typical piece of the advancement procedure. This segment spreads devices and strategies that can assist you with troubleshooting undertakings..

Error Message in Internet Explorer

The most essential approach to find blunders is by turning on mistake data in your program. Of course, Internet Explorer demonstrates a mistake symbol in the status bar when a blunder happens on the page.

error message in internet explorer

Double tapping this symbol takes you to a discourse box appearing about the particular blunder that happened. Enable the option, select Tools -Internet Options -Advanced tab. After click on Display a Notification About Every Script Error.Error Notification

Error Notifications:

Mistake notices that appear on Console or through Internet Explorer exchange boxes are the aftereffect of both sentence structure and runtime blunders. These mistake notices incorporate the line number at which the blunder happened. On the off chance that you are utilizing Firefox, at that point, you can tap on the mistake accessible in the blunder reassure to go to the definite line in the content having a mistake.

Way to debug the Scrip:
Use JavaScript Validator

One approach to check your JavaScript code for weird bugs is to run it through a program that checks it to ensure it is substantial and that it pursues the official linguistic structure principles of the language. These projects are called approving parsers or only validators for short, and regularly accompany business HTML and JavaScript editors.Javascript Validator

Use JavaScript Debugger

A debugger is an application that places all parts of content execution under the control of the software engineer. Debuggers give fine-grained power over the condition of the content through an interface that enables you to analyze and set qualities just as control the progression of execution. When content has been stacked into a debugger, it very well may be run one line at any given moment or taught to stop at certain breakpoints. When execution is stopped, the software engineer can analyze the condition of the content and its factors so as to decide whether something is wrong. You can likewise watch factors for changes in their qualities.
Javascript Debugger

Image Map on Java Script

Image map in JavaScript is an image already on that a web page it gives different connects to explore to other web pages or a few segments of a similar web page. we can say those different connections as hotspots. We can use any shape such as Polygon, Square and React angle. On the off chance that we need to make a rectangular image map, at that point you need two distinctive coordinates, for example, upper right and base left. On the off chance that you need to make a roundabout image map, at that point you need focus co-ordinate. In the event that we need to make a polygon image map, at that point you need a diverse number of co-ordinates. What’s more, last, on the off chance that we need to make a pentagon shape image map, at that point you need five co-ordinates. Use the MAP component to characterize image maps. Each image map has a one of a kind name. Consequently, the name property is required in the MAP component. we can add use map credit to the IMG component to relate an image map with an image.
ImagemapImagemap Output

 JavaScript – Browsers Compatibility

When we are Developing any web pages or using JavaScript code it’s very important to know which browser and version of the browser our web page are running because we need to handle the code in such a way that it should be compatible across all the browser.

Example:

includes  (): method in JavaScript determines whether an array contains a certain value in its entries, it will return true or false based on the value passed.

Internet  Explorer Browser does not support this method we will get an exception “includes() function undefined” for this we need to use an alternative solution indexOf().

Here comes the browser compatibly issue we need to handle this kind of issue so that it does not break our functionality.

We have built-in object “navigator” in JavaScript to get the information about the browser where your web page is running.

Navigator Properties

There are several Navigator Properties that you can use in when you create when pages

  • appCodeName

This object variable returns a string that contains the code name of the browser.

Example: Mozilla for Chrome and Microsoft Internet Explorer for Internet Explorer.

  • appVersion

This object variable returns string which contains information like such as its language and compatibility

  • language

This object variable returns string which contains the language that is used by the browser

Example:”en-us”

  • mim Types

This object variable returns Array which contains the  MIME Type supported by the browser.

Example:”en-us”

  • platform

This object variable returns string which contains the information about which platform the browser complied
Example: “Win32”

  • plugins

This object variable returns Array which contains the information about all the plugins installed in the browser

Example: “Win32”

  • userAgent

This object variable returns a string that contains information like such as its language and compatibility.

Navigator Methods

  • java enabled()

This Function Returns Boolean value check whether java is enabled in the browser.

  • plugins.refresh()

This Function Returns Array of plugins which is newly installed and with older plugins too in the         browser

  • preference(name,value)
  • taintEnabled()

This Function Returns Boolean value check whether tainting is enabled in the browser.

Example:

<html>
<body>
<script>
var SampleArr = [‘Besant-BTM’,’Besant-HSR’];
var browser = navigator.userAgent;
var ie = (browser.indexOf(‘MSIE’) !=  -1);
var browserVersion = navigation.appVersion;
var chrome = (browser.indexOf(‘Mozilla’) !=  -1);
/*checking browser and handling code based on the browser compatibily*/
If(!Ie){
If(SampleArr.includes(‘Besant-BTM’)){
Document.write(‘Other than IE Browser’);
}
}else{
If(SampleArr.indexOf(‘Besant-BTM’) > -1){
Document.write(‘ IE Browser’);
}
}
Document.write(‘ <br> Browser Version </br>:’+ browserVersion);
</script>
</body>
</html>

Output :

Other than IE Browser

Browser Version </br>: 5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like  Gecko) Chrome/74.0.3729.169 Safari/537.36

JavaScript Built-in Functions

Number Methods

Constructor() : It is a blueprint for creating and initializing for an object created.

Example:

<body>
<script type = "text/javascript">
var example = new example ( 99.23);
document.write("example.constructor() is : " + example.constructor);
</script>
</body>

toExponential(): It is a method that is used for representing a string or a number in the Exponential format.

Example:

<body>
<script type = "text/javascript">
var num = 94.822;
var example = example.toExponential();
document.write("num.toExponential() is : " + val );
</script>
</body>

The expected output for the above example is 94.822e+1

toFixed(): This is a method of freezing the digits that have to appear towards the right side of the decimal number.

Example:

<body>
<script type = "text/javascript">
var example = 986.023;
document.write("example.toFixed() is : " + example.toFixed());
document.write("example.toFixed(6) is : " + example.toFixed(6));
</script>
</body>

In the above example, the expected output is

986
023000

toLocaleString(): It is a method that is used to convert a number into a string format.

Example:

<body>
<script type = "text/javascript">
var example = new Number(843.18299);
document.write(example.toLocaleString());
</script>
</body>

Expected output

843.18299

toPrecision(): It is a method that signifies the total number of digits to be displayed irrespective of the decimal digits.

Example:

<body>
<script type = "text/javascript">
var example = new Number(9.4822456);
document.write("example.toPrecision(4) is " + example.toPrecision());
document.write("example.toPrecision(1) is " + example.toPrecision(1));
</script>
</body>

Expected output is

482
9

toString() : It is a method of representing a value that is given in the string format that uses radix( It is an integer that ranges from 2 – 36 indicating base the use of representing numeric values) as a first argument.

Example :

<body>
<script type = "text/javascript">
example = new exampleber(15);
document.write("example.toString() is " + example.toString());
document.write("example.toString(2) is " + example.toString(2));
document.write("example.toString(4) is " + example.toString(4));
</script>
</body>

Expected output is

99

1100011

1203

valueOf() :

This method represents the primitive value of the specified integer number.

Example:

<body>
<script type = "text/javascript">
var example = new exampleber(94.822);
document.write("example.valueOf() is " + example.valueOf());
</script>
</body>

Expected output is

822

Boolean Methods

toSource(): It is a method that returns a string that contains the source code of the object.

Example :

<script type="text/javascript">
function employee(name ,jobtitle ,born)
{
this.name=name;
this.jobtitle=jobtitle;
this.born=born;
}
var employe =new employee("MSP","Developer",1996);
document.write(employe.toSource());
</script>

Expected Output is

({name:"MSP", jobtitle:"Developer", born:1996})

toString(): This is a method that returns either ‘true’ or ‘false’ depending on the value that has passed from the source.

Example :

<body>
<script type = "text/javascript">
var bool = new Boolean(true);
document.write( "bool.toString is : " + bool.toString() );
</script>
</body>

Expected output is

true

valueOf(): This is a method that returns a number representing the primitive value specified.

Example :

<script type="text/javascript">
var example=0/0;
document.write("Output : " + example.valueOf());
</script>

Expected Output

“NaN”

String Methods

charAt(): This method in javascript is used to specify the position of the Character or Alphabet in a string by passing the Index.

Example :

<body>
<script type = "text/javascript">
var position = new positioning( "I am coding" );
document.writeln("position.charAt(2) is:" + position.charAt(1));
document.writeln("position.charAt(6) is:" + position.charAt(3));
</script>
</body>

Expected output is

charAt(2) is: a
charAt(6) is: o

charCodeAt(): This method returns the number that has a Unicode value of a character at the given index.

Example:

<body>
<script type = "text/javascript">
var str = new String( "my name is Software" );
document.write("str.charCodeAt(0) is:" + str.charCodeAt(0));
document.write("<br />str.charCodeAt(4) is:" + str.charCodeAt(1));
document.write("<br />str.charCodeAt(11) is:" + str.charCodeAt(11));
</script>
</body>

Expected output is

charCodeAt(0) is:109
charCodeAt(4) is:97
charCodeAt(11) is:83

concat(): This method combines two string and merges it as a single string.

Example:

<body>
<script type = "text/javascript">
var str1 = new String( "Hello" );
var str2 = new String( "Prashanth Reddy" );
var str3 = str1.concat( str2 );
document.write("Concatenated String :" + str3);
</script>
</body>

Expected output is

“Concatenated String  : Hello Prashanth Reddy”

indexOf() : This method returns the index of the string that we are searching for and returns the index of the string and -1 if the string that is being searched is not found.

Example:

<body>
<script type = "text/javascript">
var str1 = new String( "Puttagunta Vijaywada" );
var index = str1.indexOf( "Vijaywada" );
document.write("indexOf found String :" + index );
document.write("<br />");
var index = str1.indexOf( "gun" );
document.write("indexOf found String :" + index );
</script>
</body>

Expected Output is

indexOf found String :11
indexOf found String :5

lastIndexOf(): This method returns the index of the last occurrence of the String that is being searched.

Example :

<body>
<script type = "text/javascript">
var str1 = new String( "health is wealth and health determines everything" );
var index = str1.lastIndexOf( "health" );
document.write("lastIndexOf found String :" + index );
</script>
</body>

Expected Output is

“lastIndexOf found health : 21”

localeCompare(): In this method, we compare any two elements and returns a positive number if the reference string is greater than the compare string and negative number if the reference string is smaller than the compare string and zero if the compare and reference strings are equivalent.

Return Value :

0 – If both the strings are equal

-1 – If the reference string has been sorted before the another string

1 – If the reference string has been sorted after another string.

Example :

a = 'n'.localeCompare('z');
document.write('a returns '+a);

Expected Output

a returns -1

This method can also be used for sorting the elements.

<body>
<script>
var elements = [ 'prashanth', 'chintu', 'mohan', 'akhil' ];
a = elements.sort((a, b) => a.localeCompare(b));
document.write(a)
</script>
</body>

Expected Output is

Akhil, chintu, mohan, prashanth.

length() :

Date Methods

Date(): This method returns the current date and time

Example :

<body>
<script type = "text/javascript">
var date = Date();
document.write("Current Date and Time is : " + date);
</script>
</body>

Expected output is

“Current Date and Time is : Sun Jun 09 2019 19:43:01 GMT+0530 (India Standard Time)”

getDate(): This method returns the current Day of the month of the system.

Example :

<body>
<script type = "text/javascript">
var date = new Date();
document.write("Date is : " + date.getDate() );
</script>
</body>

Expected Output is

“Date is : 09”

getFullYear(): This method returns the current year of the system or any Year(if specified explicitly).

Example :

<body>
<script type = "text/javascript">
var dt = new Date("July 19, 1996 19:15:00");
document.write("year is: " + dt.getFullYear() );
</script>
</body>

Expected output is

“Year is : 1996”

getHours(): This method returns the hour of the current system or the hours that are specified according to the current system.

Example :

<body>
<script type = "text/javascript">
var date = new Date();
document.write("Hours: " + date.getHours() );
</script>
</body>

Expected Output is

“Hours : 19”

getMilliseconds(): This method returns the milliseconds of the current system.

Example :

<body>
<script type = "text/javascript">
var date = new Date( );
document.write("Milliseconds : " + date.getMilliseconds() );
</script>
</body>

Expected output is

“125”

getMinutes(): This method returns the minutes of the current system.

Example :

 <body>
<script type = "text/javascript">
var date = new Date( );
document.write("Minutes : " + date.getMilliseconds() );
</script>
</body>

Expected output is

“Minutes : 10”

getMonth(): This method returns the current month of the system or the month that is specified according to the current local system format.

Example :

<body>
<script type = "text/javascript">
var date = new Date( );
document.write("Month : " + date.getMonth() );
</script>
</body>

Expected output is

“Month : 06”

getSeconds(): This method returns the current seconds of the system or the seconds that are specified according to the current local system.

Example :

<body>
<script type = "text/javascript">
var date = new Date( );
document.write("Seconds : " + date.getSeconds() );
</script>
</body>

Expected output is

“Seconds : 20”

getTime(): This method returns the numeric value of the current time of the system or the numeric value of the current Time that is specified according to the system.

Example :

<body>
<script type = "text/javascript">
var date = new Date( );
document.write("Time : " + date.getTime() );
</script>
</body>

Expected output is

“Time : 1560092090667”

getTimezoneOffset() : This methods returns uses Greenwich Mean Time(GMT) and returns the time-zone offset in minutes for the current locale.

Example :

<body>
<script type = "text/javascript">
var date = new Date();
var offsetTimeZone = dt.getTimezoneOffset();
document.write("offsetTimeZone : " + offsetTimeZone);
</script>
</body>

Expected output is

“offsetTimeZone : -330”

getUTCDate(): This method returns the integer of the current Date according to the Universal time.

Example :

<body>
<script type = "text/javascript">
var date = new Date( "January 13, 1997 23:15:20" );
document.write("UTC Date is : " + date.getUTCDate() );
</script>
</body>

Expected Output is

“UTC Date is :9”

getUTCDay(): This method returns integer value(days of the week) ranging from 0 – 6 i.e, which indicates 0 for Sunday, 1 for Monday and so on.

Example :

<body>

<script type = "text/javascript">
var date = new Date( "July 19, 1996 23:15:20" );
document.write("UTC Day : " + date.getUTCDay() );
</script>
</body>

Expected Output is

“UTC Day is :5”.

getUTCFullYear(): This method returns the Year that is entered in the local system date format according to the universal time.

Example :

<body>
<script type = "text/javascript">
var dt = new Date( "June 9, 2019 23:15:20" );
document.write("UTC Full Year : " + dt.getUTCFullYear() );
</script>
</body>

Expected output is

“UTC Full Year : 2019”

getUTCHours(): This method returns an integer in the range 0 – 23 by the date is given with respect to the Universal time.

Example :

<body>
<script type = "text/javascript">
var date = new Date();
document.write("UTC Hours : " + date.getUTCHours() );
</script>
</body>

Expected Output is

“UTC Hours : 15”

getUTCMilliseconds(): This method returns the integer which ranges from 0 – 999 dates given with respect to the universal time.

Example :

 <body>
<script type = "text/javascript">
var date = new Date();
document.write("UTC Milli seconds : " + date.getUTCMilliseconds() );
</script>
</body>

Expected Output is

“923”

getUTCMinutes(): This method returns the integer which ranges from 0 – 59 dates given with respect to the universal time.

Example :

<body>
<script type = "text/javascript">
var date = new Date();
document.write("UTC Minutes : " + date.getUTCMinutes() );
</script>
</body>

Expected output is

“UTC Minutes : 34”

getUTCMonth(): This method returns an integer ranging from 0 – 11 as per the data entered in the system, where 0 indicates January, 1 indicates February and so on.

Example :

<body>
<script type = "text/javascript">
var date = new Date();
document.write("UTC Month : " + date.getUTCMonth() );
</script>
</body>

Expected Output is

“UTC Month : 5”

getUTCSeconds(): This method returns the integer from 0 – 59 as per the date is given by the system according to the Universal time.

Example :

<body>
<script type = "text/javascript">
var date = new Date();
document.write("UTC Seconds : " + date.getUTCSeconds());
</script>
</body>

Expected Output is

“45”

getYear(): This method returns the current year in the specified date as per the universal time. The value that will be returned by the getYear() will be the Current Year that is being given minus 1900.

Example :

<body>
<script type = "text/javascript">
var date = new Date();
document.write("get Depricated Year : " + date.getYear() );
</script>
</body>

Expected Output is

“get Depricated Year : 119”

setDate(): This method allows the user to set the date dynamically for a particular month according to the local time.

Example:

<body>
<script type = "text/javascript">
var date = new Date( "Aug 15, 2019 22:30:00" );
date.setDate( 24 );
document.write( date );
</script>
</body>

Expected Output is

“Mon Aug 19 2019 23:30:00 GMT+0530 (India Standard Time)”.

setFullYear(): This method allows to set a full year that has been received from the system.

Example :

<body>
<script type = "text/javascript">
var date = new Date( "Aug 28, 2019 23:30:00" );
date.setFullYear( 1947 );
document.write( date );
</script>
</body>

Expected Output is

“Mon Aug 28 1947 23:30:00 GMT+0530 (India Standard Time)”.

setHours(): This method allows to set hours dynamically received from the local system.

Example :

<body>
<script type = "text/javascript">
var date = new Date( "Jan 13, 1997 23:30:00" );
date.setHours( 02 );
document.write( date );
</script>
</body>

Expected output is

Thu Jan 13, 1997 02:30:00 GMT+0530 (India Standard Time)

setMilliseconds(): This method is used to set milliseconds for a particular date with respect to local time.

Example :

<body>
<script type = "text/javascript">
var date = new Date( "Aug 28, 2008 23:30:00" );
date.setMilliseconds( 1010 );
document.write( date );
</script>
</body>

Expected output is

“Thu Aug 28 2008 23:30:01 GMT+0530 (India Standard Time)”

setMinutes() : This method is used to set Minutes for a particular date dynamically.

Example :

<body>
<script type = "text/javascript">
var date = new Date( "Jul 19, 1997 23:30:00" );
date.setMinutes( 45 );
document.write( date );
</script>
</body>

Expected output is

“Thu Jul 19, 1997 23:45:00 GMT+0530 (India Standard Time)”

setMonth(): This method is used to set a Month for a particular date dynamically.

Example :

<body>
<script type = "text/javascript">
var date = new Date( "Aug 15, 2019 23:30:00" );
date.setMonth( 11 );
document.write( date );
</script>
</body>

Expected Output is

“Fri Dec 15 2019 23:30:00 GMT+0530 (India Standard Time)”

setSeconds(): This method is used to set the seconds for the data received from the system.

Example :

<body>
<script type = "text/javascript">
var date = new Date( "May 07, 1999 23:30:00" );
date.setSeconds( 80 );
document.write( date );
</script>
</body>

Expected Output is

“Thu May 07, 1999 23:31:20 GMT+0530 (India Standard Time)”.

setTime(): This method is used to reset the date by setting the time which is represented by the milliseconds e from January 1, 1970, 00:00:00 UTC.

Example :

<body>
<script type = "text/javascript">
var date = new Date( "Jul 19, 2019 23:30:00" );
date.setTime( 5000000 );
document.write( date );
</script>
</body>

Expected output is

“Thu Jan 01, 1970 06:53:20 GMT+0530 (India Standard Time)”

setUTCDate(): This method is used to set the date dynamically that is received from the local system.

Example:

<body>
<script type = "text/javascript">
var date = new Date( "Dec 18, 1996 23:30:00" );
date.setUTCDate( 20 );
document.write( date );
</script>
</body>

Expected Output is

“Fri Dec 20, 1996  23:30:00 GMT+0530 (India Standard Time)”

setUTCFullYear(): This method allows the user to set the full-year dynamically according to the universal time.

Example :

<body>
<script type = "text/javascript">
var date = new Date( "Dec 31, 1995  23:30:00" );
date.setUTCFullYear( 2006 );
document.write( date );
</script>
</body>

Expected Output is

“Mon Dec 31, 2006 23:30:00 GMT+0530 (India Standard Time)”

setUTCHours(): This method is used to set the Hour dynamically with respect to the data received from the local system.

Example :

<body>
<script type = "text/javascript">
var dt = new Date( "Aug 19, 2017 23:30:00" );
dt.setUTCHours( 15 );
document.write( dt );
</script>
</body>

Expected output is

“Sat Aug 19, 2017, 20:30:00 GMT+0530 (India Standard Time)”.

setUTCMilliseconds(): This method allows the user to set the milliseconds in the specified date with respect to a universal format.

Example :

<body>
<script type = "text/javascript">
var date = new Date( "Jul 19, 2001 23:30:00" );
date.setUTCMilliseconds( 1100 );
document.write( date );
</script>
</body>

Expected Output is

“Thu Jul 19, 2001 23:30:01 GMT+0530 (India Standard Time)”

setUTCMinutes(): This method allows the user to set the minutes in the specified date with respect to a universal format.

Example :

<body>
<script type = "text/javascript">
var date = new Date( "Aug 28, 2008 13:30:00" );
date.setUTCMinutes( 65 );
document.write( date );
</script>
</body>

Expected output is

“Thu Aug 28 2008 14:35:00 GMT+0530 (India Standard Time)”

setUTCMonth(): This method allows the user to set the month in the specified date with respect to a universal format.

Example :

<body>
<script type = "text/javascript">
var date = new Date( "Aug 28, 2008 13:30:00" );
date.setUTCMonth( 2 );
document.write( date );
</script>
</body>

Expected output is

“Fri Mar 28 2008 13:30:00 GMT+0530 (India Standard Time)”

toDateString(): This method allows the user to set the year in the specified date with respect to a universal format.

Example :

<body>
<script type = "text/javascript">
var date = new Date( "Jan 1, 1999 13:30:00" );
date.setYear( 2000 );
document.write( date );
</script>
</body>

Expected output is

“Fri Jan 1, 2000 13:30:00 GMT+0530 (India Standard Time)”

setYEAR(): This method returns the data that is received in a human-readable form.

Example :

<body>
<script type = "text/javascript">
var date = new Date(1993, 6, 28, 14, 39, 7);
document.write( "Formated Date : " + date.toDateString() );
</script>
</body>

Expected output is

“Formated Date : Wed Jul 28 1993”

toLocaleDateString(): This method is used to convert a date to a string by returning the only the Date received.

Example :

<body>
<script type = "text/javascript">
var date = new Date(1993, 7, 28, 14, 39, 7);
document.write( "Formated Date : " +date.toLocaleDateString());
</script>
</body>

Expected Output is

“Formated Date : 7/28/1993”

toLocaleString(): This method converts a date to a String format using the system’s local time zone(Date format varies from region to region i.e India à 10-6-2019, US à 6/10/2019).

Example :

<body>
<script type = "text/javascript">
var date = new Date(2012, 6, 10, 14, 39, 7);
document.write( "Formated Date : " + date.toLocaleString());
</script>
</body>

Expected Output is

Formatted Date : 6/10/2012, 2:39:07 PM

toLocaleTimeString(): This method converts the time into String format displaying the current time of the system.

Example :

<body>
<script type = "text/javascript">
var date = new Date(1993, 6, 28, 14, 39, 7);
document.write( "Formated Date : date.toLocaleTimeString());
</script>
</body>

Expected Output is

Formated Date : 10:56:07 AM

toSource(): This method returns the string which contains the source code of the object.

Example :

<body>
<script type = "text/javascript">
var date = new Date(1993, 6, 28, 14, 39, 7);
document.write( "Formated Date : " + date.toSource() );
</script>
</body>

Expected Output is

Formated Date : (new Date(743850547000))

toString(): This method converts the current Date and Time object and returns a string format.

Example :

<body>
<script type = "text/javascript">
var dateobject = new Date(1993, 6, 28, 14, 39, 7);
stringobj = dateobject.toString();
document.write( "String received is  : " + stringobj );
</script>
</body>

Expected Output is

String received is : Wed Jul 28 1993 14:39:07 GMT+0530 (India Standard Time)

to Time string() : This method returns only the time part of the entire data object in a human-readable form.

Example :

 <body>
<script type = "text/javascript">
var dateobject = new Date(2019, 7, 19, 14, 39, 7);
document.write( ‘Time received is ’+dateobject.toTimeString());
</script>
</body>

Expected output is

Time received is 14:39:07 GMT+0530 (India Standard Time)

toUTCString(): This method accepts the date and returns in the form of the String using the Universal Time Convention(UTC).

Example :

<body>
<script type = "text/javascript">
var date = new Date(2019,12, 18, 14, 39, 7);
document.write( date.toUTCString() );
</script>
</body>

Expected Output is

Wed, 28 Jul 1993 09:09:07 GMT

valueOf(): This method uses the primitive value of the Date object received and returns the number of milliseconds from 01 Jan 1970.

Example :

<body>
<script type = "text/javascript">
var dateobject = new Date(2019, 4, 28, 14, 39, 7);
document.write( dateobject.valueOf() );
</script>
</body>

Expected output is

743850547000

Math Properties

 E \: This property is a Euler’s constant and the base of natural algorithms which is approximately equal to 718281828459045.

Example :

<body>
<script type = "text/javascript">
var property_value = Math.E
document.write("Property Value is :" + property_value);
</script>
</body>

Expected Output is

Property Value is :2.718281828459045

LN2(): This property returns the logarithmic value of 2.

Example :

<body>
<script type = "text/javascript">
var Logarthamic value = Math.LN2
document.write("Logarthamic value is : " + Logarthamic value);
</script>
</body>

Expected output is

Logarthamic value is : 0.6931471805599453

LN10(): This property returns the logarithmic value of 10.

Example :

<body>
<script type = "text/javascript">
var Logarthamic value = Math.LN2
document.write("Logarthamic value is : " + Logarthamic value);
</script>
</body>

Expected output is

Logarthamic value is : 0.6931471805599453

LOG2E(): This property returns the logarithmic value of E to the base 2.

Example :

<body>
<script type = "text/javascript">
var Logarthamic value = Math.LOG2E
document.write("Logarthamic value is : " + Logarthamic value);
</script>
</body>

Expected output is

Logarthamic value is : 1.4426950408889633

LOG10E(): This property returns the logarithmic value of E to the base 10.

Example :

<body>
<script type = "text/javascript">
var Logarthamic value = Math.LOG2E
document.write("Logarthamic value is : " + Logarthamic value);
</script>
</body>

Expected output is

Logarthamic value is : 0.4342944819032518

PI: Pi is a ratio of the circumference of a circle to its diameter.

Example :

<body>
<script type = "text/javascript">
var Pi_value = Math.PI
document.write("PI value is : " + Pi_value);
</script>
</body>

Expected output is

PI value is : 3.141592653589793

SQRT1_2: This property returns the square root of 1 over 2 i.e Sqrt(1/2).

Example :

<body>
<script type = "text/javascript">
var Pi_value = Math.SQRT1_2
document.write("Square root  of 1/2 is : " + Pi_value);
</script>
</body>

Expected output is

Square root  of 1/2 is : 0.7071067811865476

SQRT2: This property returns the square root of 2.

Example :

<body>
<script type = "text/javascript">
var Pi_value = Math.SQRT2
document.write("Square root  of 2 is : " + Pi_value);
</script>
</body>

Expected output is

Square root  of 2 is : 1.4142135623730951

Math Methods

Abs: This method returns the absolute value of a number.

Example :

<body>
<script type = "text/javascript">
var value = Math.abs(-99);
document.write("absolute value is: " + value );
var value = Math.abs(null);
document.write (“absolute value is: " + value );
var value = Math.abs("msp");
document.write("absolute value is  : " + value );
</script>
</body>

Expected output is

absolute value is : 99
absolute value is : 0
absolute value is : NaN

Acos: This method returns a numeric constant -1 to 1 if the value is given is in the range and NaN if it is outside the range.

Example :

<body>
<script type = "text/javascript">
var value = Math.acos(null);
document.write("acos value is : " + value );
var value = Math.acos(30);
document.write("acos value is  : " + value );
var value = Math.acos("string");
document.write("acos value is  : " + value );
</script>
</body>

Expected output is

acos value is : 1.5707963267948966
acos value is : NaN
acos value is : NaN

asin() : This method returns numeric constant ranging from –pi/2 to pi/2 i.e (1.5707963267948966, -1.5707963267948966) and NaN if the value is out of range.

Example :

<body>
<script type = "text/javascript">
var value = Math.abs(null);
document.write("asin value is: " + value );
var value = Math.abs(-1);
document.write (“asin value is: " + value );
var value = Math.abs("msp");
document.write("asin value is  : " + value );
</script>
</body>

Expected output is

asin value is : 0
asin value is : -1.5707963267948966
asin value is : NaN

atan() : This method returns numeric constant ranging from –pi/2 to pi/2 i.e (1.5707963267948966, -1.5707963267948966).

Example :

<body>
<script type = "text/javascript">
var value = Math.abs(0.5);
document.write("asin value is: " + value );
var value = Math.abs(30);
document.write (“asin value is: " + value );
var value = Math.abs("msp");
document.write("asin value is  : " + value );
</script>
</body>

Expected output is

asin value is : 0.4636476090008061
asin value is : 1.5374753309166493
asin value is : NaN

atan2: This method returns numeric constant ranging from –pi/2 to pi/2 i.e (1.5707963267948966, -1.5707963267948966) which represents the angle theta of two different points(a,b).

Example :

<body>
<script type = "text/javascript">
var value = Math.atan2(90,15);
document.write("atanw value is : " + value );
var value = Math.atan2(15,90);
document.write("atan2 value is : " + value );
var value = Math.atan2(+Infinity, -Infinity);
document.write("atan2 value is : " + value );
</script>
</body>

Expected Output is

Theta value is : 1.4056476493802699
Theta value is : 0.16514867741462683
Theta value is : 2.356194490192345

ceil(): This method returns uses the decimal number and returns the greater number which is near or equal to a number.

Example :

<body>
<script type = "text/javascript">
var value = Math.ceil(90,15);
document.write("Theta value is : " + value );
var value = Math.ceil(15,90);
document.write("Theta value is : " + value );
var value = Math.ceil(+Infinity, -Infinity);
document.write("Theta value is : " + value );
</script>
</body>

cos(): This method returns the cosine value of a number which returns a numeric value constant between -1 to 1.

Example :

<body>
<script type = "text/javascript">
var value = Math.cos(90);
document.write("cosine value is : " + value );
var value = Math.cos(30);
document.write("cosine value is : " + value );
var value = Math.cos(-1);
document.write("cosine value is : " + value );
</script>
</body>

Expected Output is

cosine value is : -0.4480736161291702
cosine value is : 0.15425144988758405
cosine value is :  0.5403023058681398

exp(): This method is a Euler’s constant where x is an argument and E is the Euler’s constant.

Example :

<body>
<script type = "text/javascript">
var value = Math.exp(1);
document.write("Euler's value is : " + value );
var value = Math.exp(0.5);
document.write("Euler's value is : " + value );
var value = Math.exp(30);
document.write("Euler's value is : " + value );
</script>
</body>

Expected Output is

Euler's value is : 2.718281828459045
Euler's value is : 1.6487212707001282
Euler's value is :  10686474581524.482

floor(): This method accepts the decimal number and returns the smaller whole number integer value.

Example :

<body>
<script type = "text/javascript">
var value = Math.floor(10.3);
document.write("floor value is : " + value );
var value = Math.floor(99.9);
document.write("floor value is : " + value );
var value = Math.floor(-2.9);
document.write('floor value is : " + value );
</script>
</body>

Expected output is

floor value is : 10
floor value is : 99
floor value is : -3

log() : This method returns the logarithmic value of the Number. However, if the number entered is negative it returns the value received is Not a Number(NaN).

Example :

<body>
<script type = "text/javascript">
var value = Math.log(10);
document.write("log value is : " + value );
var value = Math.log(0);
document.write("log value is : " + value );
var value = Math.log(-1);
document.write('log value is : " + value );
</script>
</body>

Expected output is

log value is : 2.302585092994046
log value is : -Infinity
log value is : NaN

max(): This method finds the largest of the numbers given, and returns the larger number.

Example :

<body>
<script type = "text/javascript">
var value = Math.max(10,30,99);
document.write("maximum value is : " + value );
var value = Math.max(1,0,-45);
document.write("maximum value is : " + value );
var value = Math.max(-1, -54);
document.write('maximum value is : " + value );
</script>
</body>

Expected output is

maximum value is : 99
maximum value is : 1
maximum value is : -1

min(): This method finds the minimum number that has been found from a given set of numbers.

Example :

<body>
<script type = "text/javascript">
var value = Math.min(10,30,99);
document.write("minimum value is : " + value );
var value = Math.min(1,0,-45);
document.write("minimum value is : " + value );
var value = Math.min(-1, -54);
document.write('minimum value is : " + value );
</script>
</body>

Expected output is

minimum value is : 10
minimum value is : -45
minimum value is : -54

pow(): This method accepts 2 parameters as input and returns a single parameter as an output, where the first parameter is the base value and the second value is exponential.

Example :

<body>
<script type = "text/javascript">
var value = Math.pow(5,2);
document.write("Exponential value is : " + value );
var value = Math.pow(10,5);
document.write("Exponential value is : " + value );
var value = Math.pow(-1,4);
document.write('Exponential value is : " + value );
</script>
</body>

Expected output is

Exponential value is : 25
Exponential value is : 100000
Exponential value is : 1

random(): This method returns a decimal number which is between 0 and 1.

Example :

<body>
<script type = "text/javascript">
var value = Math.random();
document.write("Random  value is : " + value );
var value = Math.random();
document.write("Random  value is : " + value );
var value = Math.random();
document.write('Random  value is : " + value );
</script>
</body>

Expected output is

Random  value is : 0.9465327861165829
Random  value is : 0.03171426575854275
Random  value is : 0.576043078064751

round(): This method accepts the decimal number and returns the nearest whole number which is an Integer.

Example :

<body>
<script type = "text/javascript">
var value = Math.round(0.8);
document.write("round  value is : " + value );
var value = Math.round(99.1);
document.write("round  value is : " + value );
var value = Math.round(-19.4);
document.write('round  value is : " + value );
</script>
</body>

Expected output is

round  value is : 1
round  value is : 99
round  value is : --19

sin(): This method accepts a decimal/whole number and returns the sine value of a number.

Example :

<body>
<script type = "text/javascript">
var value = Math.sin(90);
document.write("sin  value is : " + value );
var value = Math.sin(0.5);
document.write("sin  value is : " + value );
var value = Math.sin(Math.PI/2);
document.write('sin  value is : " + value );
</script>
</body>

Expected output is

sin  value is : 0.8939966636005578
sin  value is : 0.479425538604203
sin  value is : 1

sqrt() : This method returns the square root of a number if the given number is positive or else the value returned is NaN.

Example :

<body>
<script type = "text/javascript">
var value = Math.sqrt(900);
document.write("Square root of a number is : " + value );
var value = Math.sqrt(0.5);
document.write("Square root of a number is : " + value );
var value = Math.sqrt(-4);
document.write('Square root of a number is : " + value );
</script>
</body>

Expected output is

Square root of a number is : 30
Square root of a number is : 0.7071067811865476
Square root of a number is : NaN

tan(): This method returns the tangent of a number that has been received which is a numeric value.

Example :

<body>
<script type = "text/javascript">
var value = Math.tan(90);
document.write("Tan value is is : " + value );
var value = Math.tan(-30);
document.write("Tan value is is : " + value );
var value = Math.tan(45);
document.write('Tan value is is : " + value );
</script>
</body>

Expected output is

Tan value is is : -1.995200412208242
Tan value is is : 6.405331196646276
Tan value is is : 1.6197751905438615

toSource(): This method returns the string ‘Math’ and it is not compatible with all the browsers.
Example :

<body>
<script type = "text/javascript">
var value = Math.toSource( );
document.write("math value is : " +  value );
</script>
</body>

Expected Output is

math value is : Math

Click Here-> Become a JavaScript Expert with Certification in 25Hours

Besant Technologies WhatsApp