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

Javascript (JS) : Name-Shubham Madne Contact-7058163037

JavaScript is a scripting language used to make webpages interactive. It can update and manipulate both HTML and CSS on a webpage. JavaScript code can be placed between <script> tags in the HTML body or head, or in an external .js file. Common JavaScript operators include arithmetic, comparison, logical, and assignment operators. JavaScript has both primitive data types like strings and numbers, as well as non-primitive types like objects and arrays. Control structures like if/else statements allow conditionally executing code.

Uploaded by

Shubham Madne
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
62 views

Javascript (JS) : Name-Shubham Madne Contact-7058163037

JavaScript is a scripting language used to make webpages interactive. It can update and manipulate both HTML and CSS on a webpage. JavaScript code can be placed between <script> tags in the HTML body or head, or in an external .js file. Common JavaScript operators include arithmetic, comparison, logical, and assignment operators. JavaScript has both primitive data types like strings and numbers, as well as non-primitive types like objects and arrays. Control structures like if/else statements allow conditionally executing code.

Uploaded by

Shubham Madne
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 54

Name-Shubham Madne

Email-madneshubham124@gmail.com
Contact-7058163037

JavaScript(js)

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.

JavaScript is the Programming Language for the Web. JavaScript can update


and change both HTML and CSS. JavaScript can calculate, manipulate and
validate data.

Example:

JavaScript provides 3 places to put the JavaScript code: within body tag, within
head tag and external JavaScript file.

<script type="text/javascript">
document.write(" ");
</script>

The script tag specifies that we are using JavaScript. The text/javascript is the
content type that provides information to the browser about the data. The
document.write() function is used to display dynamic content through
JavaScript. We will learn about document object in detail later.

There are 3 places to put our JavaScript code:-


Between the body tag of html
<html>
<head> </head>
<body>
<script type="text/javascript">
function msg(){
alert("Hello");
}
</script>
</body>
</html>
Between the head tag of html
<html>
<head>
<script type="text/javascript">
function msg(){
alert("Hello");
}
</script>
</head>
<body> </body>
</html>

In external JavaScript file


We can create external JavaScript file and embed it in many html page. It
provides code re usability because single JavaScript file can be used in several
html pages. An external JavaScript file must be saved by .js extension. It is
recommended to embed all JavaScript files into a single file. It increases the
speed of the webpage.

We provide the source of js file in html file (index.html)

<html>
<head>
<script type="text/javascript" src="message.js"></script>
</head>
<body>
<p>Hello </p>
</body>
</html>

Advantages of External JavaScript:


It helps in the reusability of code in more than one HTML file.
It allows easy code readability.
It is time-efficient as web browsers cache the external js files, which further
reduces the page loading time.
It enables both web designers and coders to work with html and js files
parallelly and separately, i.e., without facing any code conflictions.
The length of the code reduces as only we need to specify the location of the js
file.
Disadvantages of External JavaScript:
The stealer may download the coder's code using the url of the js file.
If two js files are dependent on one another, then a failure in one file may affect
the execution of the other dependent file.
The web browser needs to make an additional http request to get the js code.
A tiny to a large change in the js code may cause unexpected results in all its
dependent files.
We need to check each file that depends on the commonly created external js
file.
If it is a few lines of code, then better to implement the internal js code.
Comment:
The JavaScript comments are meaningful way to deliver message. It is used to
add information about the code, warnings or suggestions so that end user can
easily interpret the code. The JavaScript comment is ignored by the JavaScript
engine i.e. embedded in the browser.
Types of JavaScript Comments:-
Single-line Comment:
<script>
// It is single line comment
document.write("hello javascript");
</script>
Multi-line Comment:
<script>
/* It is multi line comment.
It will not be displayed */
document.write("example of javascript multiline comment");
</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).
 Name must start with a letter (a to z or A to Z), underscore( _ ), or
dollar( $ ) sign.
 After first letter we can use digits (0 to 9), for example value1.
 JavaScript variables are case sensitive, for example x and X are different
variables.

Correct JavaScript variables


var a = 34;
var _shubh="hello";

Incorrect JavaScript variables


var 334=34;
var *aa=340;

There are 2 types of variables;

1. Local variable:
A JavaScript local variable is declared inside block or function. It is
accessible within the function or block only.
<script>
If(a==b){
var y=20;//Js Local variable
}
</script>

2. 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.
<script>
var s=34;//gloabal variable
function a(){
document.writeln(data);
}
function b(){
document.writeln(data);
}
a();//calling Js function
b();
</script>

Javascript Data Types:


JavaScript provides different data types to hold different types of values. There
are two types of data types in Js.
Primitive data type
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.

var a=40;//holding number


var b="Rahul";//holding string

Primitive data types:


There are five types of primitive data types in Js are

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

Non-primitive data types:


The non-primitive data types are

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:

var sum=10+20;
Here, + is the arithmetic operator and = is the assignment operator.

There are following types of operators in JavaScript.

Arithmetic Operators
Comparison (Relational) Operators
Bitwise Operators
Logical Operators
Assignment Operators
Special Operators

1.Arithmetic Operators
+ Addition ex-10+20 = 30
- Subtraction ex-20-10 = 10
* Multiplication ex-10*20 = 200
/ Division ex-20/10 = 2
% Modulus (Remainder) ex-20%10 = 0
++ Increment ex-var a=10; a++; Now a = 11
-- Decrement ex-var a=10; a--; Now a = 9

2.Comparison Operators
== Is equal to ex-10==20 = false
=== Identical (equal and of same type) ex-10==20 = false
!= Not equal to ex-10!=20 = true
!== Not Identical ex-20!==20 = false
> Greater than ex-20>10 = true
>= Greater than or equal to ex-20>=10 = true
< Less than ex-20<10 = false
<= Less than or equal to ex-20<=10 = false

3.Bitwise Operators
& Bitwise AND ex- (10==20 & 20==33) = false
| Bitwise OR ex- (10==20 | 20==33) = false
^ Bitwise XOR ex- (10==20 ^ 20==33) = false
~ Bitwise NOT ex- (~10) = -10
<< Bitwise Left Shift ex- (10<<2) = 40
>> Bitwise Right Shift ex- (10>>2) = 2
>>> Bitwise Right Shift with Zero ex- (10>>>2) = 2
4.Logical Operators
&& Logical AND ex- (10==20 && 20==33) = false
|| Logical OR ex- (10==20 || 20==33) = false
! Logical Not ex-!(10==20) = true

5.Assignment Operators
= Assign ex-10+10 = 20
+= Add and assign ex-var a=10; a+=20; Now a = 30
-= Subtract and assign ex-var a=20; a-=10; Now a = 10
*= Multiply and assign ex-var a=10; a*=20; Now a = 200
/= Divide and assign ex-var a=10; a/=2; Now a = 5
%= Modulus and assign ex-var a=10; a%=2; Now a = 0

6.Special Operators
(?:) Conditional Operator returns value based on the condition. It is like
if-else.
, Comma Operator allows multiple expressions to be evaluated as single
statement.
delete Delete Operator deletes a property from the object.
in In Operator checks if object has the given property
instanceof checks if the object is an instance of given type
new creates an instance (object)
typeof checks the type of object.
void it discards the expression's return value.
yield checks what is returned in a generator by the generator's iterator.

JavaScript If-else statements:


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.

If Statement
If else statement
if else if statement

1) If statement:
It evaluates the content only if expression is true. The signature of JavaScript if
statement is given below.
if(expression){
//content to be evaluated
}

Example:-
<script>
var a=20;
if(a>10){
document.write("value of a is greater than 10");
}
</script>

2) If...else Statement
It evaluates the content whether condition is true of false. The syntax of
JavaScript if-else statement is given below.
if(expression){
//content to be evaluated if condition is true
}
else{
//content to be evaluated if condition is false
}

Example:-
<script>
var a=20;
if(a%2==0){
document.write("a is even number");
}
else{
document.write("a is odd number");
}
</script>

3)If...else if statement
It evaluates the content only if expression is true from several expressions. The
signature of JavaScript if else if statement is given below.
if(expression1){
//content to be evaluated if expression1 is true
}
else if(expression2){
//content to be evaluated if expression2 is true
}
else if(expression3){
//content to be evaluated if expression3 is true
}
else{
//content to be evaluated if no expression is true
}

Example:-
<script>
var a=20;
if(a==10){
document.write("a is equal to 10");
}
else if(a==15){
document.write("a is equal to 15");
}
else if(a==20){
document.write("a is equal to 20");
}
else{
document.write("a is not equal to 10, 15 or 20");
}
</script>

JavaScript Switch statement:


The JavaScript switch statement is used to execute one code from multiple
expressions. It is just like else if statement that we have learned in previous
page. But it is convenient than if..else..if because it can be used with numbers,
characters etc.

The signature of JavaScript switch statement is given below.

switch(expression){
case value1:
code to be executed;
break;
case value2:
code to be executed;
break;
......

default:
code to be executed if above values are not matched;
}

Example:-
<script>
var grade='B';
var result;
switch(grade){
case 'A':
result="A Grade";
break;
case 'B':
result="B Grade";
break;
case 'C':
result="C Grade";
break;
default:
result="No Grade";
}
document.write(result);
</script>

JavaScript Loops:
The JavaScript loops are used to iterate the piece of code using for, while, do
while or for-in loops. It makes the code compact. It is mostly used in array.

There are four types of loops in JavaScript.

for loop
while loop
do-while loop
for-in loop

1) For loop
The JavaScript for loop iterates the elements for the fixed number of times. It
should be used if number of iteration is known. The syntax of for loop is given
below.

for (initialization; condition; increment)


{
code to be executed
}

Example:-
<script>
for (i=1; i<=5; i++)
{
document.write(i + "<br/>")
}
</script>

2) While loop
The JavaScript while loop iterates the elements for the infinite number of times.
It should be used if number of iteration is not known. The syntax of while loop
is -

while (condition)
{
code to be executed
}

Example:-
<script>
var i=11;
while (i<=15)
{
document.write(i + "<br/>");
i++;
}
</script>

3) do while loop
The JavaScript do while loop iterates the elements for the infinite number of
times like while loop. But, code is executed at least once whether condition is
true or false. The syntax of do while loop is -

do{
code to be executed
}while (condition);

<script>
var i=21;
do{
document.write(i + "<br/>");
i++;
}while (i<=25);
</script>

4) JavaScript for in loop


The JavaScript for in loop is used to iterate the properties of an object.

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

Advantage of JavaScript function


There are mainly two advantages of JavaScript functions.

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


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
The syntax of declaring function is given below.

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


//code to be executed
}

Example:-
<script>
function msg(){
alert("hello! this is message");
}
</script>
<input type="button" onclick="msg()" value="call function"/>

Js Function Arguments:-
We can call function by passing arguments.

Example:-
<script>
function getcube(number){
alert(number*number*number);
}
</script>
<form>
<input type="button" value="click" onclick="getcube(4)"/>
</form>

Function with Return Value:-


We can call function that returns a value and use it in our program.

Example:-
<script>
function getInfo(){
return "hello javatpoint! How r u?";
}
</script>
<script>
document.write(getInfo());
</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.

Syntax
new Function ([arg1[, arg2[, ....argn]],] functionBody)
Parameter
arg1, arg2, .... , argn - It represents the argument used by function.

functionBody - It represents the function definition.

JavaScript Function Methods:-


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 Array:
JavaScript array is an object that represents a collection of similar type of
elements.

There are 3 ways to construct array in JavaScript

By array literal
By creating instance of Array directly (using new keyword)
By using an Array constructor (using new keyword)
1) JavaScript array literal
The syntax of creating array using array literal is

var arrayname=[value1,value2.....valueN];

Example:-
<script>
var emp=["Sonoo","Vimal","Ratan"];
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br/>");
}
</script>

2) JavaScript Array directly (new keyword)


The syntax of creating array directly is
var arrayname=new Array();
Here, new keyword is used to create instance of array.

Example:-
<script>
var i;
var emp = new Array();
emp[0] = "Arun";
emp[1] = "Varun";
emp[2] = "John";

for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>

3) JavaScript array constructor (new keyword)


Here, you need to create instance of array by passing arguments in constructor
so that we don't have to provide value explicitly.
Example:
<script>
var emp=new Array("Jai","Vijay","Smith");
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
JavaScript String
The JavaScript string is an object that represents a sequence of characters.

There are 2 ways to create string in JavaScript

By string literal
By string object (using new keyword)

1) By string literal
The string literal is created using double quotes. The syntax of creating string
using string literal is
var stringname="string value";

Example:
<script>
var str="This is string literal";
document.write(str);
</script>

2) By string object (using new keyword)


The syntax of creating string object using new keyword is

var stringname=new String("string literal");


Here, new keyword is used to create instance of string.
Example:
<script>
var stringname=new String("hello javascript string");
document.write(stringname);
</script>

JavaScript - The Date Object:


The Date object is a datatype built into the JavaScript language. Date objects are
created with the new Date( ) as shown below.

Once a Date object is created, a number of methods allow you to operate on it.
Most methods simply allow you to get and set the year, month, day, hour,
minute, second, and millisecond fields of the object, using either local time or
UTC (universal, or GMT) time.

Syntax
You can use any of the following syntaxes to create a Date object using Date()
constructor.

new Date( )
new Date(milliseconds)
new Date(datestring)
new Date(year,month,date[,hour,minute,second,millisecond ])
Note − Parameters in the brackets are always optional.

Here is a description of the parameters −


No Argument − With no arguments, the Date() constructor creates a Date object
set to the current date and time.

milliseconds − When one numeric argument is passed, it is taken as the internal


numeric representation of the date in milliseconds, as returned by the getTime()
method. For example, passing the argument 5000 creates a date that represents
five seconds past midnight on 1/1/70.

datestring − When one string argument is passed, it is a string representation of


a date, in the format accepted by the Date.parse() method.

7 agruments − To use the last form of the constructor shown above. Here is a
description of each argument −

year − Integer value representing the year. For compatibility (in order to avoid
the Y2K problem), you should always specify the year in full; use 1998, rather
than 98.

month − Integer value representing the month, beginning with 0 for January to
11 for December.

date − Integer value representing the day of the month.

hour − Integer value representing the hour of the day (24-hour scale).

minute − Integer value representing the minute segment of a time reading.

second − Integer value representing the second segment of a time reading.

millisecond − Integer value representing the millisecond segment of a time


reading.
Date Properties
Here is a list of the properties of the Date object along with their description.

1 constructor
Specifies the function that creates an object's prototype.

2 prototype
The prototype property allows you to add properties and methods to an object

In the following sections, we will have a few examples to demonstrate the usage
of different Date properties.

Date Methods
Here is a list of the methods used with Date and their description.

1 Date()
Returns today's date and time

2 getDate()
Returns the day of the month for the specified date according to local time.

3 getDay()
Returns the day of the week for the specified date according to local time.

4 getFullYear()
Returns the year of the specified date according to local time.
5 getHours()
Returns the hour in the specified date according to local time.

6 getMilliseconds()
Returns the milliseconds in the specified date according to local time.

7 getMinutes()
Returns the minutes in the specified date according to local time.

8 getMonth()
Returns the month in the specified date according to local time.

9 getSeconds()
Returns the seconds in the specified date according to local time.

10 getTime()
Returns the numeric value of the specified date as the number of milliseconds
since January 1, 1970, 00:00:00 UTC.

11 getTimezoneOffset()
Returns the time-zone offset in minutes for the current locale.

12 getUTCDate()
Returns the day (date) of the month in the specified date according to universal
time.

13 getUTCDay()
Returns the day of the week in the specified date according to universal time.
14 getUTCFullYear()
Returns the year in the specified date according to universal time.

15 getUTCHours()
Returns the hours in the specified date according to universal time.

16 getUTCMilliseconds()
Returns the milliseconds in the specified date according to universal time.

17 getUTCMinutes()
Returns the minutes in the specified date according to universal time.

18 getUTCMonth()
Returns the month in the specified date according to universal time.

19 getUTCSeconds()
Returns the seconds in the specified date according to universal time.

Browser Object Model (BOM):


The Browser Object Model (BOM) is used to interact with the browser.

The default object of browser is window means you can call all the functions of
window by specifying window or directly. For example:

The Window Object:


The window object is supported by all browsers. It represents the browser's
window.

All global JavaScript objects, functions, and variables automatically become


members of the window object.

Global variables are properties of the window object.

Global functions are methods of the window object.

Even the document object (of the HTML DOM) is a property of the window
object:

window.document.getElementById("header");
is the same as:

document.getElementById("header");

Window Size:
Two properties can be used to determine the size of the browser window.

Both properties return the sizes in pixels:

window.innerHeight - the inner height of the browser window (in pixels)


window.innerWidth - the inner width of the browser window (in pixels)
The browser window (the browser viewport) is NOT including toolbars and
scrollbars.

Example
let w = window.innerWidth;
let h = window.innerHeight;

Some other methods:


window.open() - open a new window
window.close() - close the current window
window.moveTo() - move the current window
window.resizeTo() - resize the current window

JavaScript HTML DOM:


Every web page resides inside a browser window which can be considered as an
object.
A Document object represents the HTML document that is displayed in that
window. The Document object has various properties that refer to other objects
which allow access to and modification of document content. The way a
document content is accessed and modified is called the Document Object
Model, or DOM. The Objects are organized in a hierarchy. This hierarchical
structure applies to the organization of objects in a Web document.

Window object − Top of the hierarchy. It is the outmost element of the object
hierarchy.
Document object − Each HTML document that gets loaded into a window
becomes a document object. The document contains the contents of the page.
Form object − Everything enclosed in the <form>...</form> tags sets the form
object.
Form control elements − The form object contains all the elements defined for
that object such as text fields, buttons, radio buttons, and checkboxes.

There are several DOMs in existence. The following sections explain each of
these DOMs in detail and describe how you can use them to access and modify
document content.

The Legacy DOM − This is the model which was introduced in early versions
of JavaScript language. It is well supported by all browsers, but allows access
only to certain key portions of documents, such as forms, form elements, and
images.

The W3C DOM − This document object model allows access and modification
of all document content and is standardized by the World Wide Web
Consortium (W3C). This model is supported by almost all the modern browsers.
The IE4 DOM − This document object model was introduced in Version 4 of
Microsoft's Internet Explorer browser. IE 5 and later versions include support
for most basic W3C DOM features.

DOM compatibility
If you want to write a script with the flexibility to use either W3C DOM or IE 4
DOM depending on their availability, then you can use a capability-testing
approach that first checks for the existence of a method or property to determine
whether the browser has the capability you desire. For example −

if (document.getElementById) {
// If the W3C method exists, use it
} else if (document.all) {
// If the all[] array exists, use it
} else {
// Otherwise use the legacy DOM
}

JavsScript OOP:
JavaScript Classes
In JavaScript, classes are the special type of functions. We can define the class
just like function declarations and function expressions.
The JavaScript class contains various class members within a body including
methods or constructor. The class is executed in strict mode. So, the code
containing the silent error or mistake throws an error.

The class syntax contains two components:

Class declarations
Class expressions
Class Declarations
A class can be defined by using a class declaration. A class keyword is used to
declare a class with any particular name. According to JavaScript naming
conventions, the name of the class always starts with an uppercase letter.
Example:
<script>
//Declaring class
class Employee
{
//Initializing an object
constructor(id,name)
{
this.id=id;
this.name=name;
}
//Declaring method
detail()
{
document.writeln(this.id+" "+this.name+"<br>")
}
}
//passing object to a variable
var e1=new Employee(10,"Rahul");
var e2=new Employee(11,"William");
e1.detail(); //calling method
e2.detail();
</script>
JavaScript Objects
A javaScript object is an entity having state and behavior (properties and
method). For example: car, pen, bike, chair, glass, keyboard, monitor etc.

JavaScript is an object-based language. Everything is an object in JavaScript.

JavaScript is template based not class based. Here, we don't create class to get
the object. But, we direct create objects.

Creating Objects in JavaScript


There are 3 ways to create objects.
1)By object literal:
<script>
emp={id:102,name:"Shyam Kumar",salary:40000}
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>

2) By creating instance of Object directly (using new keyword):


<script>
var emp=new Object();
emp.id=101;
emp.name="Ravi Malik";
emp.salary=50000;
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>

3) By using an object constructor (using new keyword):


<script>
function emp(id,name,salary){
this.id=id;
this.name=name;
this.salary=salary;
}
e=new emp(103,"Vimal Jaiswal",30000);

document.write(e.id+" "+e.name+" "+e.salary);


</script>

JavaScript Constructor Function:


In JavaScript, a constructor function is used to create objects.
For example,
// constructor function
function Person () {
this.name = 'John',
this.age = 23
}

// create an object
const person = new Person();
In the above example, function Person() is an object constructor function.

To create an object from a constructor function, we use the new keyword.

Note:-
Other OOP concepts are similar in other languages like java and C++
JavaScript - Errors & Exceptions Handling:
There are three types of errors in programming: (a) Syntax Errors, (b) Runtime
Errors, and (c) Logical Errors.

Syntax Errors:
Syntax errors, also called parsing errors, occur at compile time in traditional
programming languages and at interpret time in JavaScript.

For example, the following line causes a syntax error because it is missing a
closing parenthesis.

<script type = "text/javascript">


<!--
window.print(;
//-->
</script>
When a syntax error occurs in JavaScript, only the code contained within the
same thread as the syntax error is affected and the rest of the code in other
threads gets executed assuming nothing in them depends on the code containing
the error.

Runtime Errors:
Runtime errors, also called exceptions, occur during execution (after
compilation/interpretation).

For example, the following line causes a runtime error because here the syntax
is correct, but at runtime, it is trying to call a method that does not exist.

<script type = "text/javascript">


<!--
window.printme();
//-->
</script>
Exceptions also affect the thread in which they occur, allowing other JavaScript
threads to continue normal execution.

Logical Errors:
Logic errors can be the most difficult type of errors to track down. These errors
are not the result of a syntax or runtime error. Instead, they occur when you
make a mistake in the logic that drives your script and you do not get the result
you expected.

You cannot catch those errors, because it depends on your business requirement
what type of logic you want to put in your program.

The try...catch...finally Statement:


The latest versions of JavaScript added exception handling capabilities.
JavaScript implements the try...catch...finally construct as well as the throw
operator to handle exceptions.

You can catch programmer-generated and runtime exceptions, but you cannot
catch JavaScript syntax errors.

Here is the try...catch...finally block syntax −

<script type = "text/javascript">


<!--
try {
// Code to run
[break;]
}

catch ( e ) {
// Code to run if an exception occurs
[break;]
}

[ finally {
// Code that is always executed regardless of
// an exception occurring
}]
//-->
</script>
The try block must be followed by either exactly one catch block or one finally
block (or one of both). When an exception occurs in the try block, the exception
is placed in e and the catch block is executed. The optional finally block
executes unconditionally after try/catch.

Examples
Here is an example where we are trying to call a non-existing function which in
turn is raising an exception. Let us see how it behaves without try...catch−

<html>
<head>
<script type = "text/javascript">
<!--
function myFunc() {
var a = 100;
alert("Value of variable a is : " + a );
}
//-->
</script>
</head>

<body>
<p>Click the following to see the result:</p>

<form>
<input type = "button" value = "Click Me" onclick = "myFunc();" />
</form>
</body>
</html>

Now let us try to catch this exception using try...catch and display a user-
friendly message. we can also suppress this message, if we want to hide this
error from a user.

<html>
<head>

<script type = "text/javascript">


<!--
function myFunc() {
var a = 100;
try {
alert("Value of variable a is : " + a );
}
catch ( e ) {
alert("Error: " + e.description );
}
}
//-->
</script>

</head>
<body>
<p>Click the following to see the result:</p>

<form>
<input type = "button" value = "Click Me" onclick = "myFunc();" />
</form>

</body>
</html>

we can use finally block which will always execute unconditionally after the
try/catch. Here is an example.
<html>
<head>

<script type = "text/javascript">


<!--
function myFunc() {
var a = 100;

try {
alert("Value of variable a is : " + a );
}
catch ( e ) {
alert("Error: " + e.description );
}
finally {
alert("Finally block will always execute!" );
}
}
//-->
</script>

</head>
<body>
<p>Click the following to see the result:</p>

<form>
<input type = "button" value = "Click Me" onclick = "myFunc();" />
</form>

</body>
</html>

The throw Statement:


we can use throw statement to raise our built-in exceptions or our customized
exceptions. Later these exceptions can be captured and we can take an
appropriate action.

Example
The following example demonstrates how to use a throw statement.

<html>
<head>

<script type = "text/javascript">


<!--
function myFunc() {
var a = 100;
var b = 0;

try {
if ( b == 0 ) {
throw( "Divide by zero error." );
} else {
var c = a / b;
}
}
catch ( e ) {
alert("Error: " + e );
}
}
//-->
</script>

</head>
<body>
<p>Click the following to see the result:</p>

<form>
<input type = "button" value = "Click Me" onclick = "myFunc();" />
</form>

</body>
</html>

we can raise an exception in one function using a string, integer, Boolean, or an


object and then we can capture that exception either in the same function as we
did above, or in another function using a try...catch block.

The onerror() Method


The onerror event handler was the first feature to facilitate error handling in
JavaScript. The error event is fired on the window object whenever an
exception occurs on the page.

<html>
<head>

<script type = "text/javascript">


<!--
window.onerror = function () {
alert("An error occurred.");
}
//-->
</script>

</head>
<body>
<p>Click the following to see the result:</p>

<form>
<input type = "button" value = "Click Me" onclick = "myFunc();" />
</form>

</body>
</html>
Output

The onerror event handler provides three pieces of information to identify the
exact nature of the error −

Error message − The same message that the browser would display for the
given error

URL − The file in which the error occurred

Line number− The line number in the given URL that caused the error
Here is the example to show how to extract this information.

Example
<html>
<head>

<script type = "text/javascript">


<!--
window.onerror = function (msg, url, line) {
alert("Message : " + msg );
alert("url : " + url );
alert("Line number : " + line );
}
//-->
</script>

</head>
<body>
<p>Click the following to see the result:</p>

<form>
<input type = "button" value = "Click Me" onclick = "myFunc();" />
</form>

</body>
</html>
Output
we can display extracted information in whatever way we think it is better.

we can use an onerror method, as shown below, to display an error message in


case there is any problem in loading an image.

<img src="myimage.gif" onerror="alert('An error occurred loading the image.')"


/>
We can use onerror with many HTML tags to display appropriate messages in
case of errors.

React Js
ReactJS is a simple, feature rich, component based JavaScript UI library. It can
be used to develop small applications as well as big, complex applications.
ReactJS provides minimal and solid feature set to kick-start a web application.

Applications of React
Few popular websites powered by React library are listed below −

Facebook, popular social media application


Instagram, popular photo sharing application
Netflix, popular media streaming application
Reddit, popular content sharing application

Instead of introducing new template language, React introduces three simple


concepts as given below −

React elements
JavaScript representation of HTML DOM. React provides an API,
React.createElement to create React Element.

JSX
A JavaScript extension to design user interface. JSX is an XML based,
extensible language supporting HTML syntax with little modification. JSX can
be compiled to React Elements and used to create user interface.

React component
React component is the primary building block of the React application. It uses
React elements and JSX to design its user interface. React component is
basically a JavaScript class (extends the React.component class) or pure
JavaScript function. React component has properties, state management, life
cycle and event handler. React component can be able to do simple as well as
advanced logic.
ReactJS Web Application Page:
ReactJS applications come as a JavaScript blob that will use the DOM interface
to write the view into the div as shown bellow.

<!doctype html>
<html>
<head>
<title>CS142 Example</title>
</head>
<body>
<div id="reactapp"></div>
<script src="./webpackOutput/reactApp.bundle.js"></script>
</body>
</html>

ReactJS tool chain:


Babel - Transpile language features (e.g. ECMAScript, JSX) to basic JavaScript
Webpack - Bundle modules and resources (CSS, images)
Output loadable with single script tag in any browser

reactApp.js - Render element into browser DOM


import React from 'react';
import ReactDOM from 'react-dom';

//ES6 Modules - Bring in


//React and web app React componets

import ReactAppView from './components/ReactAppView';


let viewTree = React.createElement(ReactAppView, null);
let where = document.getElementById('reactapp');
ReactDOM.render(viewTree, where);

//Renders the tree of React elements (single component


//named ReactAppView) into the browser's DOM at the
//div with id=reactapp.

components/ReactAppView.js - ES6 class definition


import React from 'react';
class ReactAppView extends React.Component {
constructor(props) { // Inherits from React.Component. props is set to the
//attributes passed to the component.
super(props);
...
}
render() { ...//Require method render() - returns React element tree of the
//Component's view.

};
export default ReactAppView;

ReactAppView render() method:


render() {
let label = React.createElement('label', null,'Name: ');
let input = React.createElement('input',
{ type: 'text', value: this.state.yourName,
onChange: (event) => this.handleChange(event) });
let h1 = React.createElement('h1', null,
'Hello ', this.state.yourName, '!');
return React.createElement('div', null, label, input, h1);
}
Returns element tree with div (label, input, and h1) elements

ReactAppView render() method w/o variables


render() {
return React.createElement('div', null,
React.createElement('label', null,'Name: '),
React.createElement('input',
{ type: 'text', value: this.state.yourName,
onChange: (event) => this.handleChange(event) }),
React.createElement('h1', null,
'Hello ', this.state.yourName, '!')
);}

Use JSX to generate calls to createElement render() { return (


render() {
return (
<div>
<label>Name: </label>
<input
type="text"
value={this.state.yourName}
onChange={(event) => this.handleChange(event)}
/>
<h1>Hello {this.state.yourName}!</h1>
</div>
);
}
● JSX makes building tree look like templated HTML embedded in JavaScript

Component state and input handling


import React from 'react';
class ReactAppView extends React.Component {
constructor(props) {
super(props);
this.state = {yourName: ""};
}
handleChange(event) {
this.setState({ yourName: event.target.value });
}
....
● Input calls to setState which causes React to call render() again

Calling React Components from events workaround:


● Create instance function bound to instance
class ReactAppView extends React.Component {
constructor(props) {
super(props);
this.state = {yourName: ""};
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
this.setState({ yourName: event.target.value });}

● Using public fields of classes with arrow functions


class ReactAppView extends React.Component {
constructor(props) {
super(props);
this.state = {yourName: ""};
}
handleChange = (event) => {
this.setState({ yourName: event.target.value });
}
● Using arrow functions in JSX
class ReactAppView extends React.Component {

handleChange(event) {
this.setState({ yourName: event.target.value });
}
render() {
return (
<input type="text" value={ this.state.yourName}
onChange={(event) => this.handleChange(event)} />
);
}

Styling with React/JSX - lots of different ways


import React from 'react';
import './ReactAppView.css';
class ReactAppView extends React.Component {

render() {
return (
<span className="xyz ">
...
</span>
);

Example of lifecycle methods - update UI every 2s


class Example extends React.Component {
...
componentDidMount() { // Start 2 sec counter
const incFunc =
() => this.setState({ counter: this.state.counter + 1 });
this.timerID = setInterval(incFunc, 2 * 1000);
}
componentWillUnmount() { // Shutdown timer
clearInterval(this.timerID);}

Stateless Components
● React Component can be function (not a class) if it only depends on props
function MyComponent(props) {
return <div>My name is {props.name}</div>;
}
Or using destructuring...
function MyComponent({name}) {
return <div>My name is {name}</div>;
}

Communicating between React components


● Passing information from parent to child: Use props (attributes)
<ChildComponent param={infoForChildComponent} />
● Passing information from child to parent: Callbacks
this.parentCallback = (infoFromChild) =>
{ /* processInfoFromChild */};
<ChildComponent callback={this.parentCallback}> />
● React Context (https://reactjs.org/docs/context.html)
Global variables for subtree of components

You might also like