Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
12 views

Javascript

Uploaded by

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

Javascript

Uploaded by

Kathan Patel
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 93

javascript

What is JavaScript

javaScript (js) is a light-weight object-oriented programming language which is used by several websites for scripting the
webpages. It is an interpreted, full-fledged programming language that enables dynamic interactivity on websites when
applied to an HTML document.
Features of JavaScript

1. All popular web browsers support JavaScript as they provide built-in execution environments.
2. JavaScript follows the syntax and structure of the C programming language. Thus, it is a structured programming
language.
3. JavaScript is a weakly typed language, where certain types are implicitly cast (depending on the operation).
4. JavaScript is an object-oriented programming language that uses prototypes rather than using classes for
inheritance.
5. It is a light-weighted and interpreted language.
6. It is a case-sensitive language.
How to add JavaScript to html

JavaScript, also known as JS, is one of the scripting (client-side scripting) languages, that is usually used in web
development to create modern and interactive web-pages. The term "script" is used to refer to the languages that are not
standalone in nature and here it refers to JavaScript which run on the client machine.
Adding JavaScript to HTML Pages

There are following three ways in which users can add JavaScript to HTML pages.

1. Embedding code
2. Inline code
3. External file
I. Embedding code:-

To add the JavaScript code into the HTML pages, we can use the <script>.....</script> tag of the HTML that wrap around
JavaScript code inside the HTML program. Users can also define JavaScript code in the <body> tag (or we can say body
section) or <head> tag because it completely depends on the structure of the web page that the users use.
1. <!DOCTYPE html >
2. <html>
3. <head>
4. <title> page title</title>
5. <script>
6. document.write(“Hello students");
7. </script>
8. </head>
9. <body>
10. <p>Inthis example we saw how to add JavaScript in the head section </p>
11. </body>
12. </html>
We can also define the JavaScript code in the <body> tags or body section.

1. <!DOCTYPE html >


2. <html>
3. <head>
4. <title> page title</title>
5. </head>
6. <body>
7. <script>
8. document.write("Welcome to Javatpoint");
9. </script>
10. <p> In this example we saw how to add JavaScript in the body section </p>
11. </body>
12. </html>
Inline code:-

Generally, this method is used when we have to call a function in the HTML event attributes. There are many cases (or
events) in which we have to add JavaScript code directly eg., OnMover event, OnClick, etc.
1. <!DOCTYPE html >
2. <html>
3. <head>
4. <title> page title</title>
5. </head>
6. <body>
7. <p>
8. <a href="#" onClick="alert('Welcome !');">Click Me</a>
9. </p>
10. <p> in this example we saw how to use inline JavaScript or directly in an HTML tag.
</p>
External file:-

We can also create a separate file to hold the code of JavaScript with the (.js) extension and later incorporate/include it into
our HTML document using the src attribute of the <script> tag. It becomes very helpful if we want to use the same code in
multiple HTML documents. It also saves us from the task of writing the same code over and over again and makes it easier
to maintain web pages.
1. <html>
2. <head>
3. <meta charset="utf-8">
4. <title>Including a External JavaScript File</title>
5. </head>
6. <body>
7. <form>
8. <input type="button" value="Result" onclick="display()"/>
9. </form>
10. <script src="hello.js">
11. </script>
12. </body>
13. </html>
Hello.js

1. function display() {
2. alert("Hello World!");
3. }
How to call JavaScript function in html?

There are many ways to call a JavaScript function in the HTML document, and it is also not a difficult task. First, we have
used one of the easiest ways to call a JavaScript

function in HTML document:

In this method, we will create and define a function in the HTML

document's head section. To invoke this function in the html document, we have to create a simple button and using the onclick event
attribute (which is an event handler) along with it, we can call the function by clicking on the button.
1. <html>
2. <head>
3. <script type = "text/javascript">
4. function myfunction() {
5. alert("how are you");
6. }
7. </script>
8. </head>
9. <body>
10. <p>Click the following button to see the function in action</p>
11. <input type = "button" onclick = "myfunction()" value = "Display">
12. </body>
13. </html>
Explanation of program

In the above-given program, we have created a simple HTML document. Inside the head section of the HTML document, we
have defined a function (e.g myfunction();) inside the script tags <script>...</script>.
1. <html>
2. <head>
3. <script type = "text/javascript">
4. function myfunction() {
5. alert("how are you");
6. }
7. </script>
JavaScript Variable
A JavaScript variable is simply a name of storage location. There are two types of variables in JavaScript : local variable
and global variable.

There are some rules while declaring a JavaScript variable (also known as identifiers).

1. Name must start with a letter (a to z or A to Z), underscore( _ ), or dollar( $ ) sign.


2. After first letter we can use digits (0 to 9), for example value1.
3. JavaScript variables are case sensitive, for example x and X are different variables.
Correct JavaScript variables

1. var x = 10;
2. var _value="sonoo";
Example of JavaScript variable

1. <script>
2. var x = 10;
3. var y = 20;
4. var z=x+y;
5. document.write(z);
6. </script>
JavaScript local variable

A JavaScript local variable is declared inside block or function. It is accessible


within the function or block only. For example:
1. <script>
2. function abc(){
3. var x=10;//local variable
4. }
5. </script>
JavaScript global variable

A JavaScript global variable is accessible from any function. A variable i.e. declared outside the function or declared with window object is known
as global variable. For example:

1. <script>
2. var data=200;//gloabal variable
3. function a(){
4. document.writeln(data);
5. }
6. function b(){
7. document.writeln(data);
8. }
9. a();//calling JavaScript function
10. b();
11. </script>
Confirm()

The confirm() method displays a dialog box with a message, an OK button, and
a Cancel button.

The confirm() method returns true if the user clicked "OK", otherwise false.

Syntax
confirm(message)
Var answer= confirm(“are you happy to continue ?”)
Example
<script>

function myFunction() {

let text;

if (confirm("Press a button!") == true) {

text = "You pressed OK!";

} else {

text = "You canceled!";

document.getElementById("demo").innerHTML = text;

</script>
Prompt() function
The prompt() method displays a dialog box that prompts the user for input.

The prompt() method returns the input value if the user clicks "OK", otherwise it returns null.

Var user= prompt(“what is your full name”)


Selecting elements by their id
To select an element of your Html page having a specific id,all you need to do is
call the document object getElementById() method,specifying as an argument the
id of the required element

<div id=”div1>

Content of div

</div>

Var mydiv=document.getElementById(“div1”)
The innerHTML Property
The innerHTML allows us to get or set the value of the HTML content inside a
particular page element
example:
<div id="div1">
<p> here is some original text</p>
</div>
HTML JavaScript

A Script is a small program which is used with HTML to make web pages more attractive, dynamic and interactive, such as
an alert popup window on mouse click. Currently, the most popular scripting language is JavaScript used for websites.

1. <!DOCTYPE html>
2. <html>
3. <body>
4. <h1>JavaScript Date and Time example</h1>
5. <button type="button"
6. onclick="document.getElementById('demo').innerHTML = Date()">
7. Click me to display Date and Time.</button>
8. <p id="demo"></p>
9. </body>
10. </html>
HTML <script> Tag

The HTML <script> tag is used to specify a client-side script. It may be an internal or external JavaScript which contains
scripting statements, hence we can place <script> tag within <body> or <head> section.

It is mainly used to manipulate images, form validation and change content dynamically. JavaScript uses
document.getElementById() method to select an HTML element.
1. <!DOCTYPE html>
2. <html>
3. <body>
4. <h2>Use JavaScript to Change Text</h2>
5. <p id="demo"></p>
6. <script>
7. document.getElementById("demo").innerHTML = "Hello JavaTpoint";
8. </script>
9. </body>
10. </html>
HTML events with JavaScript

n event is something which user does, or browser does such as mouse click or page loading are examples of events, and
JavaScript comes in the role if we want something to happen on these events.
<!DOCTYPE html>

<html>

<body>

<h2>Click Event Example</h2>

<p>Click on the button and you can see a pop-up window with a message</p>

<input type="button" value="Click" onclick="alert('Hi,how are you')">

</body>

</html>
HTML can have following events such as:

● Form events: reset, submit, etc.


● Select events: text field, text area, etc.
● Focus event: focus, blur, etc.
● Mouse events: select, mouseup, mousemove, mousedown, click, dblclick, etc.
Use External Script

1. <script type="text/javascript" src="URL "></script>


2. <!DOCTYPE html>
3. <html>
4. <head>
5. <script type="text/javascript" src="external.js"></script>
6. </head>
7. <body>
8. <h2>External JavaScript Example</h2>
9. <form onsubmit="fun()">
10. <label>Enter your name:</label><br>
11. <input type="text" name="uname" id="frm1"><br>
12. <label>Enter your Email-address:</label><br>
13. <input type="email" name="email"><br>
14. <input type="submit">
15. </form>
16. </body>
17. </html>
1. function fun() {
2. var x = document.getElementById("frm1").value;
3. alert("Hi"+" "+x+ "you have successfully submitted the details");
4. }
The HTML noscript Element

The <nosscript> element provides us an alternate way to create content for the users that either have browsers that don?t support the
JavaScript or have disabled JavaScript in the browser.
1. <!DOCTYPE html>
2. <html>
3. <body>
4. <h1>Thenoscript element</h1>
5. <p>If the user have a browser with JavaScript disabled will show the text inside the noscript element and "Hello World!" will not be
displayed.</p>
6. <script>
7. document.write("Hello World!")
8. </script>
9. <noscript>Sorry, your browser may not support JavaScript! orJavaScript is disabled in your browser </noscript>
10.
11. </body>
12. </html>
How to add comment In HTML

You can add comments in your HTML file using <! -- ... --> tag. So if you will write anything between theses comment tag that
will be treated as comment and browser will not read it.

Syntax
<! -- Write commented text here -->

Multiline Comment
1. <!---
2. Your code is commented.
3. Write description of code.
4. It will not display at webpage.
5. -->
Javascript Data Types

JavaScript provides different data types to hold different types of values. There are two types of data types in JavaScript.

1. Primitive data type

2. Non-primitive (reference) data type

JavaScript is a dynamic type language, means you don't need to specify type of the variable because it is dynamically used by
JavaScript engine. You need to use var here to specify the data type. It can hold any type of values such as numbers, strings etc. For
example:

1. var a=40;//holding number


2. var b="Rahul";//holding string
JavaScript primitive data types

String
represents sequence of characters e.g. "hello"
Number
represents numeric values e.g. 100
Boolean
represents boolean value either false or true
Undefined
represents undefined value
Null
represents null i.e. no value at all
JavaScript non-primitive data types

Object

represents instance through which we can access members

Array

represents group of similar values

RegExp

represents regular expression


JavaScript Operators

JavaScript operators are symbols that are used to perform operations on


operands. For example:
1. var sum=10+20;
2.
There are following types of operators in JavaScript.

1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Bitwise Operators
4. Logical Operators
5. Assignment Operators
6. Special Operators
7.
+

Addition

10+20 = 30

Subtraction

20-10 = 10

Multiplication

10*20 = 200

Division

20/10 = 2

Modulus (Remainder)

20%10 = 0

++

Increment

var a=10; a++; Now a = 11

--

Decrement

var a=10; a--; Now a = 9


JavaScript If-else

The JavaScript if-else statement is used to execute the code whether condition is true or false. There are three forms of if
statement in JavaScript.

1. If Statement
2. If else statement
3. if else if statement
4.
JavaScript If statement
It evaluates the content only if expression is true. The signature of JavaScript if statement is given below.

1. if(expression){
2. //content to be evaluated
3. }
4.
1. <script>
2. var a=20;
3. if(a>10){
4. document.write("value of a is greater than 10");
5. }
6. </script>
JavaScript If...else Statement

It evaluates the content whether condition is true of false. The syntax of JavaScript if-else statement is given below.

1. if(expression){
2. //content to be evaluated if condition is true
3. }
4. else{
5. //content to be evaluated if condition is false
6. }
1. <script>
2. var a=20;
3. if(a%2==0){
4. document.write("a is even number");
5. }
6. else{
7. document.write("a is odd number");
8. }
9. </script>
1. <script>
2. var a=20;
3. if(a==10){
4. document.write("a is equal to 10");
5. }
6. else if(a==15){
7. document.write("a is equal to 15");
8. }
9. else if(a==20){
10. document.write("a is equal to 20");
11. }
12. else{
13. document.write("a is not equal to 10, 15 or 20");
14. }
15. </script>
JavaScript Functions

JavaScript functions are used to perform operations. We can call JavaScript function many times to reuse the code.

Advantage of JavaScript function

1. Code reusability: We can call a function several times so it save coding.


2. Less coding: It makes our program compact. We don’t need to write many lines of code each time to perform a
common task.
JavaScript Function Syntax

1. function functionName([arg1, arg2, ...argN]){


2. //code to be executed
3. }
JavaScript Function Example

1. <script>
2. function msg(){
3. alert("hello! this is message");
4. }
5. </script>
6. <input type="button" onclick="msg()" value="call function"/>
JavaScript Function Arguments

1. script>
2. function getcube(number){
3. alert(number*number*number);
4. }
5. </script>
6. <form>
7. <input type="button" value="click" onclick="getcube(4)"/>
8. </form>
Function with Return Value

1. <script>
2. function getInfo(){
3. return "hello javatpoint! How r u?";
4. }
5. </script>
6. <script>
7. document.write(getInfo());
8. </script>
JavaScript Function Object

In JavaScript, the purpose of Function constructor is to create a new Function object. It executes the code globally.
However, if we call the constructor directly, a function is created dynamically but in an unsecured way.

1. new Function ([arg1[, arg2[, ....argn]],] functionBody)


2.
Parameter

arg1, arg2, .... , argn - It represents the argument used by function.

functionBody - It represents the function definition.


Method
Description
apply()

It is used to call a function contains this value and a single array of arguments.

bind()

It is used to create a new function.

call()

It is used to call a function contains this value and an argument list.

toString()

It returns the result in a form of a string


JavaScript Function Object Examples

1. <script>
2. var add=new Function("num1","num2","return num1+num2");
3. document.writeln(add(2,5));
4. </script>
Let's see an example to display the power of provided value.
1. <script>
2. var pow=new Function("num1","num2","return Math.pow(num1,num2)");
3. document.writeln(pow(2,3));
4. </script>
JavaScript Array

JavaScript array is an object that represents a collection of similar type of elements.

There are 3 ways to construct array in JavaScript

1. By array literal
2. By creating instance of Array directly (using new keyword)
3. By using an Array constructor (using new keyword)
4.
JavaScript array literal
The syntax of creating array using array literal is given below:

1. var arrayname=[value1,value2.....valueN];
2. <script>
3. var emp=["Sonoo","Vimal","Ratan"];
4. for (i=0;i<emp.length;i++){
5. document.write(emp[i] + "<br/>");
6. }
7. </script>
2) JavaScript Array directly (new keyword)

1. var arrayname=new Array();


2.
3. <script>
4. var i;
5. var emp = new Array();
6. emp[0] = "Arun";
7. emp[1] = "Varun";
8. emp[2] = "John";
9.
10. for (i=0;i<emp.length;i++){
11. document.write(emp[i] + "<br>");
12. }
13. </script>
JavaScript Events

The change in the state of an object is known as an Event. In html, there are various events which represents that some
activity is performed by the user or by the browser. When javascript

code is included in HTML


, js react over these events and allow the execution. This process of reacting over the events is called Event Handling. Thus, js handles
the HTML events via Event Handlers.

For example, when a user clicks over the browser, add js code, which will execute the task to be performed on the event.

Some of the HTML events and their event handlers are:


Mouse events:
Keyboard events:

Event Performed :Keydown & Keyup

Event Handler:onkeydown & onkeyup

Description:When the user press and then release the key


Click Event
1. <html>
2. <head> Javascript Events </head>
3. <body>
4. <script language="Javascript" type="text/Javascript">
5. <!--
6. function clickevent()
7. {
8. document.write("This is JavaTpoint");
9. }
10. //-->
11. </script>
12. <form>
13. <input type="button" onclick="clickevent()" value="Who's this?"/>
14. </form>
15. </body>
16. </html>
17.
MouseOver Event

1. <html>
2. <head>
3. <h1> Javascript Events </h1>
4. </head>
5. <body>
6. <script language="Javascript" type="text/Javascript">
7. <!--
8. function mouseoverevent()
9. {
10. alert("This is JavaTpoint");
11. }
12. //-->
13. </script>
14. <p onmouseover="mouseoverevent()"> Keep cursor over me</p>
15. </body>
16. </html>
17.
Focus Event

1. <html>
2. <head> Javascript Events</head>
3. <body>
4. <h2> Enter something here</h2>
5. <input type="text" id="input1" onfocus="focusevent()"/>
6. <script>
7. <!--
8. function focusevent()
9. {
10. document.getElementById("input1").style.background=" aqua";
11. }
12. //-->
13. </script>
14. </body>
15. </html>
16.
Keydown Event

1. <html>
2. <head> Javascript Events</head>
3. <body>
4. <h2> Enter something here</h2>
5. <input type="text" id="input1" onkeydown="keydownevent()"/>
6. <script>
7. <!--
8. function keydownevent()
9. {
10. document.getElementById("input1");
11. alert("Pressed a key");
12. }
13. //-->
14. </script>
15. </body>
16. </html>
17.
Load event

1. <html>
2. <head>Javascript Events</head>
3. </br>
4. <body onload="window.alert('Page successfully loaded');">
5. <script>
6. <!--
7. document.write("The page is loaded successfully");
8. //-->
9. </script>
10. </body>
11. </html>
12.
JavaScript addEventListener()

The addEventListener() method is used to attach an event handler to a particular element. It does not override the existing event handlers. Events
are said to be an essential part of the JavaScript. A web page responds according to the event that occurred. Events can be user-generated or
generated by API's. An event listener is a JavaScript's procedure that waits for the occurrence of an event.

The addEventListener() method is an inbuilt function of JavaScript. We can add multiple event handlers to a particular element without
overwriting the existing event handlers.

Syntax
1. element.addEventListener(event, function, useCapture);

function: It is also a required parameter. It is a JavaScript function which responds to the event occur.
It is a simple example of using the addEventListener() method. We have to click the given HTML button to see the effect.

1. <!DOCTYPE html>
2. <html>
3. <body>
4. <p> Example of the addEventListener() method. </p>
5. <p> Click the following button to see the effect. </p>
6. <button id = "btn"> Click me </button>
7. <p id = "para"></p>
8. <script>
9. document.getElementById("btn").addEventListener("click", fun);
10. function fun() {
11. document.getElementById("para").innerHTML = "Hello World" + "<br>" + "Welcome to the javaTpoint.com";
12. }
13. </script>
14. </body>
15. </html>
16.
1. <!DOCTYPE html>
2. <html>
3. <body>
4. <p> This is an example of adding multiple events to the same element. </p>
5. <p> Click the following button to see the effect. </p>
6. <button id = "btn"> Click me </button>
7. <p id = "para"></p>
8. <p id = "para1"></p>
9. <script>
10. function fun() {
11. alert("Welcome to the javaTpoint.com");
12. }
13.
14. function fun1() {
15. document.getElementById("para").innerHTML = "This is second function";
16.
17. }
18. function fun2() {
19. document.getElementById("para1").innerHTML = "This is third function";
20. }
21. var mybtn = document.getElementById("btn");
22. mybtn.addEventListener("click", fun);
23. mybtn.addEventListener("click", fun1);
24. mybtn.addEventListener("click", fun2);
25. </script>
26. </body>
27. </html>
28.
Mouse over example
1. <!DOCTYPE html>
2. <html>
3. <body>
4. <p> This is an example of adding multiple events of different type to the same element. </p>
5. <p> Click the following button to see the effect. </p>
6. <button id = "btn"> Click me </button>
7. <p id = "para"></p>
8. <script>
9. function fun() {
10. btn.style.width = "50px";
11. btn.style.height = "50px";
12. btn.style.background = "yellow";
13. btn.style.color = "blue";
14. }
15.
16. function fun1() {
17. document.getElementById("para").innerHTML = "This is second function";
18.
19. }
20. function fun2() {
21. btn.style.width = "";
22. btn.style.height = "";
23. btn.style.background = "";
24. btn.style.color = "";
25. }
26. var mybtn = document.getElementById("btn");
27. mybtn.addEventListener("mouseover", fun);
28. mybtn.addEventListener("click", fun1);
29. mybtn.addEventListener("mouseout", fun2);
30. </script>
31. </body>
32. </html>
33.
JavaScript onclick event

The onclick event generally occurs when the user clicks on an element. It allows the programmer to execute a JavaScript's
function when an element gets clicked. This event can be used for validating a form, warning messages and many more.

Now, we see the syntax of using the onclick event in HTML


and in javascript
(without addEventListener() method or by using the addEventListener() method).
In HTML
1. <element onclick = "fun()">

In JavaScript
1. object.onclick = function() { myScript };

In JavaScript by using the addEventListener() method


1. object.addEventListener("click", myScript);
2.
Example1 - Using onclick attribute in HTML

In this example, we are using the HTML onclick

1. <!DOCTYPE html>
2. <html>
3. <head>
4. <script>
5. function fun() {
6. alert("Welcome to the javaTpoint.com");
7. }
8. </script>
9. </head>
10. <body>
11. <h3> This is an example of using onclick attribute in HTML. </h3>
12. <p> Click the following button to see the effect. </p>
13. <button onclick = "fun()">Click me</button>
14. </body>
15. </html>
Example2 - Using JavaScript

1. <!DOCTYPE html>
2. <html>
3. <head>
4. <title> onclick event </title>
5. </head>
6. <body>
7. <h3> This is an example of using onclick event. </h3>
8. <p> Click the following text to see the effect. </p>
9. <p id = "para">Click me</p>
10. <script>
11. document.getElementById("para").onclick = function() {
12. fun()
13. };
14. function fun() {
15. document.getElementById("para").innerHTML = "Welcome to the javaTpoint.com";
16. document.getElementById("para").style.color = "blue";
17. document.getElementById("para").style.backgroundColor = "yellow";
18. document.getElementById("para").style.fontSize = "25px";
19. document.getElementById("para").style.border = "4px solid red";
20. }
21. </script>
22. </body>
23. </html>
24.
Example3 - Using addEventListener() method

1. <!DOCTYPE html>
2. <html>
3. <head>
4. </head>
5. <body>
6. <h3> This is an example of using click event. </h3>
7. <p> Click the following text to see the effect. </p>
8. <p id = "para">Click me</p>
9. <script>
10. document.getElementById("para").onclick = function() {
11. fun()
12. };
13. function fun() {
14. document.getElementById("para").innerHTML = "Welcome to the javaTpoint.com";
15. document.getElementsByTagName("body")[0].style.color = "blue";
16. document.getElementsByTagName("body")[0].style.backgroundColor = "lightgreen";
17. document.getElementsByTagName("body")[0].style.fontSize = "25px";
18. document.getElementById("para").style.border = "4px solid red";
19. }
20. </script>
21. </body>
22. </html>
23.
JavaScript dblclick event

The dblclick event generates an event on double click the element. The event fires when an element is clicked twice in a
very short span of time. We can also use the JavaScript's addEventListener() method to fire the double click event.

, we can use the ondblclick attribute to create a double click event.

In HTML
1. <element ondblclick = "fun()">
2.
1. <!DOCTYPE html>
2. <html>
3. <head>
4. </head>
5.
6. <body>
7. <h1 id = "heading" ondblclick = "fun()"> Hello world :):) </h1>
8. <h2> Double Click the text "Hello world" to see the effect. </h2>
9. <p> This is an example of using the <b> ondblclick </b> attribute. </p>
10. <script>
11. function fun() {
12. document.getElementById("heading").innerHTML = " Welcome to the javaTpoint.com ";
13. }
14. </script>
15. </body>
16. </html>
17.
What is Exception Handling

In programming, exception handling is a process or method used for handling the abnormal statements in the code and
executing them. It also enables to handle the flow control of the code/program. For handling the code, various handlers are
used that process the exception and execute the code. For example, the Division of a non-zero value with zero will result
into infinity always, and it is an exception. Thus, with the help of exception handling, it can be executed and handled.

In exception handling:

A throw statement is used to raise an exception. It means when an abnormal condition occurs, an exception is thrown using
throw.
Types of Errors
While coding, there can be three types of errors in the code:

1. Syntax Error: When a user makes a mistake in the pre-defined syntax of a programming language, a syntax error may
appear.
2. Runtime Error: When an error occurs during the execution of the program, such an error is known as Runtime error.
The codes which create runtime errors are known as Exceptions. Thus, exception handlers are used for handling
runtime errors.
3. Logical Error: An error which occurs when there is any logical mistake in the program that may not produce the
desired output, and may terminate abnormally. Such an error is known as Logical error.
4.
Exception Handling Statements

● throw statements
● try…catch statements
● try…catch…finally statements.
JavaScript try…catch

A try…catch is a commonly used statement in various programming languages. Basically, it is used to handle the error-prone
part of the code. It initially tests the code for all possible errors it may contain, then it implements actions to tackle those
errors (if occur). A good programming approach is to keep the complex code within the try…catch statements.

try{} statement: Here, the code which needs possible error testing is kept within the try block. In case any error occur, it passes to the
catch{} block for taking suitable actions and handle the error. Otherwise, it executes the code written within.

catch{} statement: This block handles the error of the code by executing the set of statements written within the block. This
block contains either the user-defined exception handler or the built-in handler. This block executes only when any
error-prone code needs to be handled in the try block. Otherwise, the catch block is skipped.
Syntax:
1. try{
2. expression; } //code to be written.
3. catch(error){
4. expression; } // code for handling the error.
5.
try…catch example

1. <html>
2. <head> Exception Handling</br></head>
3. <body>
4. <script>
5. try{
6. var a= ["34","32","5","31","24","44","67"]; //a is an array
7. document.write(a); // displays elements of a
8. document.write(b); //b is undefined but still trying to fetch its value. Thus catch block will be invoked
9. }catch(e){
10. alert("There is error which shows "+e.message); //Handling error
11. }
12. </script>
13. </body>
14. </html>
Throw Statement

Throw statements are used for throwing user-defined errors. User can define and throw their own custom errors. When throw statement is executed, the
statements present after it will not execute. The control will directly pass to the catch block.

Syntax:
1. throw exception;

try…catch…throw syntax
1. try{
2. throw exception; // user can define their own exception
3. }
4. catch(error){
5. expression; } // code for handling exception.
6.
1. <html>
2. <head>Exception Handling</head>
3. <body>
4. <script>
5. try {
6. throw new Error('This is the throw keyword'); //user-defined throw statement.
7. }
8. catch (e) {
9. document.write(e.message); // This will generate an error message
10. }
11. </script>
12. </body>
13. </html>
14.
try…catch…finally statements

Finally is an optional block of statements which is executed after the execution of try and catch statements. Finally block does not
hold for the exception to be thrown. Any exception is thrown or not, finally block code, if present, will definitely execute. It does not
care for the output too.

Syntax:
1. try{
2. expression;
3. }
4. catch(error){
5. expression;
6. }
7. finally{
8. expression; } //Executable code
try…catch…finally example

1. <!DOCTYPE html>
2. <html>
3. <body>
4. <pre>
5. <script>
6. try
7. {
8. var a=2;
9. if(a==2)
10. document.writeln("ok");
11. }
12. catch(Error)
13. {
14. document.writeln("Error found"+e.message);
15. }
16. finally
17. {
18. document.writeln("Value of a is 2 ");
19. }
20.
21. </script>
22. </pre>
23. </body>
24. </html>
25.
26.

You might also like