[Go to site: main page, start]

0% found this document useful (0 votes)
14 views98 pages

JavaScript Basics and Features Explained

Chapter Four provides an overview of JavaScript, a lightweight, object-oriented programming language used for web development. It covers features, syntax, variable types, data types, operators, and methods for input and output, emphasizing its role in creating dynamic and interactive web applications. The chapter also discusses the organization of JavaScript code, including inline, internal, and external scripts, as well as comments and type conversion.

Uploaded by

dagimdanecho34
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views98 pages

JavaScript Basics and Features Explained

Chapter Four provides an overview of JavaScript, a lightweight, object-oriented programming language used for web development. It covers features, syntax, variable types, data types, operators, and methods for input and output, emphasizing its role in creating dynamic and interactive web applications. The chapter also discusses the organization of JavaScript code, including inline, internal, and external scripts, as well as comments and type conversion.

Uploaded by

dagimdanecho34
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Chapter Four

JavaScript
Introduction
• 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.
• With JavaScript, users can build modern web applications to interact
directly without reloading the page every time.
• The traditional website uses js to provide several forms of interactivity and
simplicity.
• Although, JavaScript has no connectivity with Java programming language.
Features of JavaScript
• All popular web browsers support JavaScript as they provide built-in execution
environments.
• JavaScript follows the syntax and structure of the C programming language. Thus,
it is a structured programming language.
• JavaScript is a weakly typed language, where certain types are implicitly cast
(depending on the operation).
• JavaScript is an object-oriented programming language that uses prototypes
rather than using classes for inheritance.
• It is a light-weighted and interpreted language.
• It is a case-sensitive language.
• JavaScript is supportable in several operating systems including, Windows, macOS,
etc.
• It provides good control to the users over the web browsers.
JavaScript Basics
• Syntax of JavaScript
• <html>
• <body>
• <h2>Welcome to JavaScript</h2>
• <script type="text/javascript">
• [Link]("JavaScript is a simple language for javatpoint learners");
• </script>
• </body>
• </html>
• 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.
3 Places to put JavaScript code
•Between the body tag of html
•Between the head tag of html
•In .js file (external javaScript)
code between the body tag
• Let’s see the simple example of JavaScript that displays alert dialog
box.
• <html>
• <body>
• <script type="text/javascript">
• alert("Hello Javatpoint");
• </script>
• </body>
• </html>
code between the head tag
• Let’s see the same example of displaying alert dialog box of JavaScript that is contained inside the head tag.
• To call function, you need to work on event. Here we are using onclick event to call msg() function.
• <html>
• <head>
• <script type="text/javascript">
• function msg(){
• alert("Hello Javatpoint");
• }
• </script>
• </head>
• <body>
• <p>Welcome to JavaScript</p>
• <form>
• <input type="button" value="click" >• </form>
• </body>
• </html>
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.
Cont’d…
[Link]
[Link] <html>
<head>
function msg(){ <script type="text/javascript" src="[Link]"></script
alert("Hello Javatpoint"); >
</head>
} <body>
<p>Welcome to JavaScript</p>
<form>
<input type="button" value="click" > </form>
</body>
</html>
JavaScript Comments
• Single Line Comments
• Single line comments start with //.
• Any text between // and the end of the line will be ignored by JavaScript (will not
be executed).
• // Change heading:
[Link]("myH").innerHTML = "My First Page";
• Multi-line Comments
• Multi-line comments start with /* and end with */.
• Any text between /* and */ will be ignored by JavaScript.
• /*
The code below will change
the heading with id = "myH"
and the paragraph with id = "myP"
in my web page:
*/
Basic JavaScript Input Output
• JavaScript is a versatile programming language used primarily for web
development.
• It allows developers to create dynamic and interactive web pages by
manipulating HTML and CSS, and handling user interactions.
• Basic Input
• Input in JavaScript typically involves obtaining data from users. This
can be done through various methods, such as:
• Using the prompt() function: This function displays a dialog box
prompting the user for input. The input is then returned as a string.
• var name = prompt("Enter your name:");
Cont’d…
• HTML input elements:
• HTML provides input elements such as <input> and <textarea> which
can be used to collect user input.
• JavaScript can then be used to retrieve the input values from these
elements.
• <input type="text" id="nameInput">
• var name = [Link]("nameInput").value;
Cont’d…
• Basic Output
• Output in JavaScript involves displaying information to users. This can be
done through various methods, such as:
• Using alert() function: This function displays a dialog box with a specified
message. It's commonly used for displaying alerts or notifications to users.
• alert("Hello, World!");
• Using [Link](): This function outputs data to the console. It's often
used for debugging purposes or displaying information to developers.
• [Link]("Hello, World!");
Cont’d…
• Manipulating HTML elements: JavaScript can manipulate HTML
elements to dynamically update content on a webpage.
• This is often done by selecting an element and modifying its innerText
or innerHTML properties.
• <p id="output"></p>
• [Link]("output").innerHTML = "Hello, World!";
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.
Cont’d…
• Correct JavaScript variables
• var x = 10;
• Int x=10;
• var _value=“Thanks";
• Incorrect JavaScript variables
• var 123=30;
• var *aa=320;
• //Example
• <html>
• <head>
• </head>
• <body>
• <p id="hh"></p>
• <script>
• var x=10;
• var $y=20;
• let a="20";
• let b=parseInt(a)
• var z=x+$y;
• //[Link](x)
• [Link]("hh").innerHTML=z;
• </script>
• </body>
• </html>
Scope Of Variables
• JavaScript local variable • JavaScript global variable
• A JavaScript local variable is • A JavaScript global variable is accessible from
declared inside block or any function.
function.
• A variable i.e. declared outside the function
• It is accessible within the or declared with window object is known as
function or block only.
global variable.
• <script>
• <script>
• function abc(){ • var data=200;//gloabal variable
• var x=10;//local variable • function a(){
•} • [Link](data);
• </script> }
Javascript Data Types
• JavaScript provides different data types to hold different types of values.
There are two types of data types in JavaScript.
• 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.
• For example:
• var a=40;//holding number
• var b=“Tinsae";//holding string
JavaScript primitive data types
Data Type Description

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


Data Type Conversion
• JavaScript variables can be converted to a new variable and another
data type:
• By the use of a JavaScript function
• Automatically by JavaScript itself//
• Converting Strings to Numbers
• The global method Number() converts a variable (or a value) into a
number.
• A numeric string (like "3.14") converts to a number (like 3.14).
• An empty string (like “ ") converts to 0.
• A non numeric string (like "John") converts to NaN (Not a Number).
Number Methods
Method Description
Number() Returns a number, converted from its
argument
parseFloat() Parses a string and returns a floating point
number
parseInt() Parses a string and returns an integer
Converting Numbers to Strings
• The global method String() can convert numbers to strings.
• It can be used on any type of numbers, literals, variables, or
expressions:
• Example
• String(x) // returns a string from a number variable x
• String(123) // returns a string from a number literal 123
• String(100 + 23) // returns a string from a number from an expression
• The Number method toString() does the same.
• <!DOCTYPE html>
• <html>
• <body>
• <h2>JavaScript Number Methods</h2>
• <p>The toString() method converts a number to a string.</p>
• <p id="demo"></p>
• <script>
• let x = 123;
• [Link]("demo").innerHTML =
• [Link]() + "<br>" +
• (123).toString() + "<br>" +
• (100 + 23).toString();
• </script>
• </body>
• </html>
Automatic Type Conversion
• When JavaScript tries to operate on a "wrong" data type, it will try to
convert the value to a "right" type.
• The result is not always what you expect:
• 5 + null // returns 5 because null is converted to 0
• "5" + null // returns "5null" because null is converted to "null"
• "5" + 2 // returns “7" because 2 is converted to "2"
• "5" - 2 // returns 3 because "5" is converted to 5
• "5" * "2" // returns 10 because "5" and "2" are converted to 5
and 2
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
Arithmetic Operators
Operator Description Example

+ 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 Comparison Operators
Operator Description Example

== Is equal to 1020 = false


=== Identical (equal and of same type) 1020 = false

! Not equal to 10!20 = true


! Not Identical 20!20 = false
> Greater than 2010 = true
>= Greater than or equal to 2010 = true

< Less than 2010 = false


<= Less than or equal to 2010 = false
JavaScript Bitwise Operators
Operator Description Example

& Bitwise AND 1020 & 2033 = false

| Bitwise OR 1020 | 2033 = false

^ Bitwise XOR 1020 ^ 2033 = false

~ Bitwise NOT 10 = 10


<< Bitwise Left Shift 102 = 40
>> Bitwise Right Shift 102 = 2
>>> Bitwise Right Shift with Zero 102 = 2
Example of bitwise &
• // Define variables
• let x = 10;//1010
• let y = 9;//0110
• 0010
• // Perform bitwise AND operation
• let result = x & y;
• // Output the result
• [Link]("The result of x & y is:", result); // Output: 8
JavaScript Logical Operators
Operator Description Example

&& Logical AND 1020 &&


2033 = false
|| Logical OR 1020 || 2033
= false
! Logical Not !1020 = true
Assignment Operators
Operator Description Example

= Assign 1010  20
+= Add and assign var a=10; a+=20; Now a
= 30
-= Subtract and assign var a=20; a-=10; Now a =
10
*= Multiply and assign var a=10; a*=20; Now a =
200
/= Divide and assign var a=10; a/2; Now a = 5

% Modulus and assign var a=10; a%2; Now a =


0
Special Operators
Operator Description
? 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.
• Example of Special Operators
• // Conditional Operator (?:)
• function checkAge(age) {
• return age >= 18 ? "Adult" : "Minor";
• }
• [Link](checkAge(20)); // Output: "Adult"
• [Link](checkAge(15)); // Output: "Minor"
• // Comma Operator (,)
• var x = 1, y = 2, z = 3;
• [Link](x, y, z); // Output: 1 2 3
• // Delete Operator (delete)
• var person = { name: "John", age: 30 };
• [Link](person); // Output: { name: "John", age: 30 }
• delete [Link];
• [Link](person); // Output: { name: "John" }
• // In Operator (in)
• var car = { make: "Toyota", model: "Camry" };
• [Link]("make" in car); // Output: true
• [Link]("year" in car); // Output: false
• // Instanceof Operator (instanceof)
• function Car(make, model) {
• [Link] = make;
• [Link] = model;
•}
• var myCar = new Car("Toyota", "Camry");
• [Link](myCar instanceof Car); // Output: true
• [Link](myCar instanceof Object); // Output: true
Control Structures (Conditional and Looping
Statements)
• 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.
• If Statement
• If else statement
• if else if statement
• JavaScript 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
• <html>
• <body>
• <script>
• var a=20;
• if(a>10){
• [Link]("value of a is greater than 10");
•}
• </script>
• </body>
• </html>
JavaScript 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
• <html>
• <body>
• <script>
• var a=20;
• if(a%2==0){
• [Link]("a is even number");
•}
• else{
• [Link]("a is odd number");
•}
• </script>
• </body>
• </html>
JavaScript 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
•}
Cont’d…
• // Define the grade variable
• let grade = 88;
• // Conditional statements to determine the grade
• if (grade >= 90 && grade < 100) {
• [Link]("Grade: A+");
• } else if (grade >= 85 && grade < 90) {
• [Link]("Grade: A");
• } else if (grade >= 80 && grade < 85) {
• [Link]("Grade: B");
• } else {
• [Link]("Grade: Below B");
• }
The switch statement
• It is a control flow statement in JavaScript used to execute a block of code based on the
value of an expression.
• It provides an alternative to chaining multiple if-else statements when there are multiple
possible execution paths based on the value of a single expression.
• switch (expression) {
• case value1:
• // Code to be executed if expression matches value1
• break;
• case value2:
• // Code to be executed if expression matches value2
• break;
• // Add more cases as needed...
• default:
• // Code to be executed if expression doesn't match any case
•}
Cont’d…
• The switch keyword starts the switch statement.
• The expression is evaluated once and compared with the values of the case
clauses.
• Each case clause specifies a value to compare the expression against.
• If the expression matches a case value, the corresponding block of code is
executed.
• The break statement terminates the switch statement and exits the switch
block. If omitted, the execution will continue to the next case or default
block.
• The default case is optional and is executed if the expression doesn't match
any of the case values.
• // Define a variable
• let day = 3;
• let dayName;
• switch (day) {
• case 1:
• dayName = "Monday";
• break;
• case 2:
• dayName = "Tuesday";
• break;
• case 3:
• dayName = "Wednesday";
• break;
• default:
•}
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
JavaScript 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
•}
• <!DOCTYPE html>
• <html>
• <body>
• <script>
• for (i=1; i<=5; i++)
•{
• [Link](i + "<br/>")
•}
• </script>
• </body>
• </html>
JavaScript 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 given below.
• while (condition)
•{
• code to be executed
•}
• <!DOCTYPE html>
• <html>
• <body>
• <script>
• var i=11;
• while (i<=15)
•{
• [Link](i + "<br/>");
• i++;
•}
• </script>
• </body>
• </html>
JavaScript 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 given below.
• do{
• code to be executed
• }while (condition);
• <!DOCTYPE html>
• <html>
• <body>
• <script>
• var i=21;
• do{
• [Link](i + "<br/>");
• i++;
• }while (i<=25);
• </script>
• </body>
• </html>
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.
Cont’d…
• JavaScript Function Syntax
• The syntax of declaring function is given below.
• function functionName([arg1, arg2, ...argN]){
• //code to be executed
•}
• <script>
• function msg(){
• alert("hello! this is message");
•}
• </script>
• <input type="button" value="call function"/>
Cont’d…
• JavaScript Function Arguments
• We can call function by passing arguments. Let’s see the example of function that
has one argument.
• <script>
• function getcube(number){
• alert(number*number*number);
•}
• </script>
• <form>
• <input type="button" value="click" >• </form>
JavaScript Function Methods

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.
• // Example object
• const person = {
• firstName: 'John',
• lastName: 'Doe',
• fullName: function() {
• return [Link] + ' ' + [Link];
• }};
• function greet(message) {
• return message + ' ' + [Link]();
• }
• // apply()
• [Link]("apply():", [Link](person, ["Hello"])); // Output: Hello John Do
• // bind()
• const boundGreet = [Link](person, "Hi");
• [Link]("bind():", boundGreet()); // Output: Hi John Doe
• // call()
• [Link]("call():", [Link](person, "Hey")); // Output: Hey John Doe
• // toString()
• const num = 10;
• [Link]("toString():", [Link]()); // Output: "10"
JavaScript DOM (Document object Model)
Document Object Model
• The document object represents the whole html document.
• When html document is loaded in the browser, it becomes a document
object.
• It is the root element that represents the html document. It has properties
and methods.
• It has properties and methods. By the help of document object, we can
add dynamic content to our web page.
• According to W3C - "The W3C Document Object Model (DOM) is a platform
and language-neutral interface that allows programs and scripts to
dynamically access and update the content, structure, and style of a
document."
Properties of document object
Methods of document object
Method Description
write("string") writes the given string on the doucment.

writeln("string") writes the given string on the doucment with


newline character at the end.

getElementById() returns the element having the given id


value.
getElementsByName() returns all the elements having the given
name value.
getElementsByTagNam returns all the elements having the given tag
e() name.
getElementsByClassNa returns all the elements having the given
me() class name.
Accessing field value by document object
• <script type="text/javascript">
• function printvalue(){
• var name=[Link];
• alert("Welcome: "+name);
•}
• </script>

• <form name="form1">
• Enter Name:<input type="text" name="name"/>
• <input type="button" value="print name"/>
• </form>
Javascript - [Link]()
method
• The [Link]() method returns the element of
specified id.
• In the previous page, we have used [Link] to
get the value of the input value.
• Instead of this, we can use [Link]() method to get
value of the input text.
• But we need to define id for the input field.
Cont’d…
• <script type="text/javascript">
• function getcube(){
• var number=[Link]("number").value;
• alert(number*number*number);
•}
• </script>
• <form>
• Enter No:<input type="text" id="number" name="number"/><br/>
• <input type="button" value="cube" >• </form>
[Link]() method
• The [Link]() method returns all the
element of specified name.
• The syntax of the getElementsByName() method is given below:
• [Link]("name")
• <script type="text/javascript">
• function totalelements()
•{
• var allgenders=[Link]("gender");
• alert("Total Genders:"+[Link]);
•}
• </script>
• <form>
• Male:<input type="radio" name="gender" value="male">
• Female:<input type="radio" name="gender" value="female">

• <input type="button" value="Total Genders">
• </form>
[Link]() method
• getElementsByTagName() method
• The [Link]() method returns all the
element of specified tag name.
• The syntax of the getElementsByTagName() method is given below:
• [Link]("name")
• getElementsByTagName Example
• <script type="text/javascript">
• function countpara(){
• var totalpara=[Link]("p");
• alert("total p tags are: "+[Link]);

•}
• </script>
• <p>This is a pragraph</p>
• <p>Here we are going to count total number of paragraphs by getElementB
yTagName() method.</p>
• <p>Let's see the simple example</p>
• <button paragraph</button>
Javascript - innerHTML
• The innerHTML property can be used to write the dynamic html on
the html document.
• It is used mostly in the web pages to generate the dynamic html such
as registration form, comment form, links etc.
• <html>
• <body>
• <script type="text/javascript" >
• function showcommentform() {
• var data="Name:<br><input type='text' name='name'><br>Comment:<br><textarea
rows='5' cols='50'></textarea><br><input type='submit' value='comment'>";
• [Link]('mylocation').innerHTML=data;
• }
• </script>
• <form name="myForm">
• <input type="button" value="comment" >• <div id="mylocation"></div>
• </form>
• </body>
• </html>
CSS in Java Script
• The HTML DOM allows JavaScript to change the style of HTML elements.
• To change the style of an HTML element, use this syntax:
• [Link](id).[Link] = new style
• <html>
<body>
<p id="p2">Hello World!</p>
<script>
[Link]("p2").[Link] = "blue";
</script>
</body>
</html>
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 Event
Event Performed Event Handler Description
click onclick When mouse click on an element

mouseover onmouseover When the cursor of the mouse comes over the
element

mouseout onmouseout When the cursor of the mouse leaves an element

mousedown onmousedown When the mouse button is pressed over the


element

mouseup onmouseup When the mouse button is released over the


element

mousemove onmousemove When the mouse movement takes place.


• <!DOCTYPE html>
• <head>
• <script>
• function MouseEvent () {
• [Link]("p1").[Link]="red";
•}
• </script>

</head>
• <body>
• <p id="p1" you clicked my by
hovering</p>
• </body>
• </html>
Exception Handling in JavaScript
• An exception signifies the presence of an abnormal condition which
requires special operable techniques.
• In programming terms, an exception is the anomalous code that
breaks the normal flow of the code.
• Such exceptions require specialized programming constructs for its
execution.
• 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.
Cont’d…
• 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.
• The thrown exception is handled by wrapping the code into the
try…catch block. If an error is present, the catch block will execute,
else only the try block statements will get executed.
• Thus, in a programming language, there can be different types of
errors which may disturb the proper execution of the program.
Types of Errors
• While coding, there can be three types of errors in the code:
• Syntax Error: When a user makes a mistake in the pre-defined syntax
of a programming language, a syntax error may appear.
• 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.
• 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.
Types of Exceptions
• EvalError: It creates an instance for the error that occurred in the eval(),
which is a global function used for evaluating the js string code.
• InternalError: It creates an instance when the js engine throws an internal
error.
• RangeError: It creates an instance for the error that occurs when a numeric
variable or parameter is out of its valid range.
• ReferenceError: It creates an instance for the error that occurs when an
invalid reference is de-referenced.
• SyntaxError: An instance is created for the syntax error that may occur
while parsing the eval().
• TypeError: When a variable is not a valid type, an instance is created for
such an error.
• URIError: An instance is created for the error that occurs when invalid
parameters are passed in encodeURI() or decodeURI().
Cont’d…
• Exception Handling Statements
• throw statements
• try…catch statements
• try…catch…finally statements.
JavaScript try…catch
• 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.
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.
• try{
• throw exception; // user can define their own exception
•}
• catch(error){
• expression; } // code for handling exception.
Example try --catch
• <html>
• <head>Exception Handling</head>
• <body>
• <script>
• try {
• throw new Error('This is the throw keyword'); //user-defined throw statement.
• }
• catch (e) {
• [Link]([Link]); // This will generate an error message
• }
• </script>
• </body>
• </html>
JavaScript Form Validation
• It is important to validate the form submitted by the user because it
can have inappropriate values.
• So, validation is must to authenticate user.
• JavaScript provides facility to validate the form on the client-side so
data processing will be faster than server-side validation.
• Most of the web developers prefer JavaScript form validation.
• Through JavaScript, we can validate name, password, email, date,
mobile numbers and more fields.
• Form validation Example
• <script>
• function validateform(){
• var name=[Link];
• var password=[Link];

• if (name==null || name==""){
• alert("Name can't be blank");
• return false;
• }else if([Link]<6){
• alert("Password must be at least 6 characters long.");
• return false;
• }
• }
• </script>
Cont’d…
• <body>
• <form name="myform" method="post" action="[Link]" > turn validateform()" >
• Name: <input type="text" name="name"><br/>
• Password: <input type="password" name="password"><br/>
• <input type="submit" value="register">
• </form>
Browser Object Model
• 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:
• [Link]("hello javascript");
• The same as alert(“Hello javascript”)
BOM
• The window object represents a window in browser. An object of
window is created automatically by the browser.
• Window is the object of browser, it is not the object of javascript. The
javascript objects are string, array, date etc
Method Description

alert() displays the alert box containing message


with ok button.
confirm() displays the confirm dialog box containing
message with ok and cancel button.
prompt() displays a dialog box to get input from the
user.
open() opens the new window.
close() closes the current window.
setTimeout() performs action after specified time like
calling function, evaluating expressions etc.
Confirm object example
• <script type="text/javascript">
• function msg(){
• var v= confirm("Are u sure?");
• if(v==true){
• alert("ok");
•}
• else{
• alert("cancel");
•} }
• </script>
• <input type="button" value="delete record" > History Object
• The JavaScript history object represents an array of URLs visited by
the user. By using this object, you can load previous, forward or any
particular page.
• The history object is the window property, so it can be accessed by:
No. Method Description

1 forward() loads the next


page.
2 back() loads the previous
page.
3 go() loads the given
page number.
Navigator object
• The JavaScript navigator object is used for browser detection. It can
be used to get browser information such as appName,
appCodeName, userAgent etc.
• The navigator object is the window property, so it can be accessed by:
• [Link]
No. Property Description
1 appName returns the name
2 appVersion returns the version
3 appCodeName returns the code name
4 cookieEnabled returns true if cookie is enabled otherwise false

5 userAgent returns the user agent


6 language returns the language. It is supported in Netscape and Firefox
only.
7 userLanguage returns the user language. It is supported in IE only.

8 plugins returns the plugins. It is supported in Netscape and Firefox only.

9 systemLanguage returns the system language. It is supported in IE only.

10 mimeTypes[] returns the array of mime type. It is supported in Netscape and


Firefox only.

11 platform returns the platform e.g. Win32.


12 online returns true if browser is online otherwise false.
Cookies in JavaScript
• A cookie is an amount of information that persists between a
server-side and a client-side.
• A web browser stores this information at the time of browsing.
• A cookie contains the information as a string generally in the form of a
name-value pair separated by semi-colons.
• It maintains the state of a user and remembers the user's information
among all the web pages.
• [Link]="name=value";
Cont’d…
• When a user sends a request to the server, then each of that request
is treated as a new request sent by the different user.
• So, to recognize the old user, we need to add the cookie with the
response from the server.
• browser at the client-side.
• Now, whenever a user sends a request to the server, the cookie is
added with that request automatically. Due to the cookie, the server
recognizes the users.
Example
• <html>
• <head>
• <script>
• function setCookie()
• {
• [Link]="username=Duke Martin";
• }
• function getCookie()
• {
• if([Link]!=0)
• {
• alert([Link]);
• }
• else
• {
• alert("Cookie not available");
• }
• }
• </script>
• <head>
Cont’.d…
• <body>
• <input type="button" value="setCookie" >• <input type="button" value="getCookie" >• <script>
• </body>
• </html>
The End of Chapter 4

Thank you!!!
Assignment(10%)
• Apply form validation including regex,exception handling in personal
websites
• Develop online quiz application using javascript

You might also like