Javascript Unit I

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 55

Unit I: Overview & Introduction to 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. It was
introduced in the year 1995 for adding programs to the webpages in the Netscape Navigator
browser. Since then, it has been adopted by all other graphical web browsers. 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.

JavaScript was introduced in 1995 as a way to add programs to web pages in the Netscape
Navigator browser. The language has since been adopted by all other major graphical web
browsers. It has made modern web applications possible—applications with which you can
interact directly, without doing a page reload for every action. But it is also used in more
traditional websites to provide various forms of interactivity and cleverness.

It is important to note that JavaScript has almost nothing to do with the programming language
named Java. The similar name was inspired by marketing considerations, rather than good
judgment. When JavaScript was introduced, the Java language was being heavily marketed and
was gaining popularity. Someone thought it was a good idea to ride on the coattails of
this success. Now we are stuck with the name.

Features of JavaScript

There are following 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.
7. JavaScript is supportable in several operating systems including, Windows, macOS, etc.
8. It provides good control to the users over the web browsers.

The development workflow


To make the job of testing your scripts easier, you want to have your text editor and browser
running simultaneously. You need to be able to switch quickly between editor and browser as
you experiment and repair any errors that may creep into your code.

The typical workflow entails the following steps:


1. Enter HTML, JavaScript, and CSS into the source documents in the text editor.
2. Save them to disk.
3. Switch to the browser.

4. Do one of the following:


_ If this is a new document, open the file through the browser’s Open menu.
_ If the document is already loaded, reload the file into the browser.
Steps 2 through 4 are actions you will take frequently.

We call this three-step sequence the save-switch-reload sequence. You will perform this
sequence so often as you script that the physical act will quickly become second nature to you.
How you arrange your application windows and effect the save-switch-reload sequence varies
according to your operating system.
In web site production, after you tweak your markup, style sheet, and scripts to your liking on
your own computer, you’ll upload them to your server using an FTP (File Transfer Protocol)
program.
There are also online editors, but for now let’s keep it simple. One of the advantages of doing
your work off-line on your own computer is that you don’t even have to have an active Internet
connection during this stage of web site development.
Selecting the right tools for the job
The best way to learn JavaScript is to type the HTML and scripting code into documents in a
text editor. Your choice of editor is up to you, although we provide some guidelines for
choosing.

Choosing a text editor


For the purposes of learning JavaScript in this book, avoid WYSIWYG (What You See Is What
You Get) web page authoring tools such as FrontPage and Dreamweaver. These tools may
come in handy later for molding your content and layout. But the examples in this book focus
more on script content (which you must type anyway), so there isn’t much HTML that you have
totype. Files for all complete web page listings in this book (except for the tutorial
chapters) also appear on the companion CD-ROM.

An important factor to consider in your choice of editor is how easy it is to save standard text
files with an .html filename extension. In the case of Windows, any program that not only saves
the file as text by default, but also enables you to set the extension to .htm or .html, prevents a
great deal of problems. If you use Microsoft Word, for example, the program tries to save files
as binary Word files — something that no web browser can load. To save the file initially as
a .txt or .html extension file requires mucking around in the Save As dialog box. This is truly a
nuisance. Perhaps more importantly, a word processor such as Microsoft Word opens with a lot
of default settings that may make desktop publishing easier but can frustrate a programmer,
such as inserting spaces around words and automatically replacing straight quotes with curly
quotes.

Setting its defaults to make it programmer-friendly will make it less useful as a word processor.
Finally, we urge you not to create documents in Word and ‘‘save them as a web page.’’ This
will generate an HTML document that will look much like the word processing document on
which it’s based, but the actual HTML coding it produces will be bloated and redundant — a far
cry from the sleek and elegant code that we hope you will be producing after you read this
book. Word just isn’t the right tool for this job.

Nothing’s wrong with using bare-essentials text editors. In Windows, that includes the Word-
Pad program or a more fully featured product such as Visual Studio or the shareware editor
called TextPad. For Mac OS X, the bundled TextEdit application is also fine. Favorites among
Mac HTML authors and scripters include BBEdit (Bare Bones Software) and SubEthaEdit
(www.codingmonkeys.de/subethaedit).
Choosing a browser
The other component that is required for learning JavaScript is the browser. You don’t have to
be connected to the Internet to test your scripts in the browser. You can perform all testing
offline. This means you can learn JavaScript and create cool, scripted web pages with a laptop
computer — even on a boat in the middle of an ocean.

The browser brand and version you use are up to you. Because the tutorial chapters in this book
teach the W3C DOM syntax, you should be using a recent browser. Any of the following will
get you through the tutorial: Internet Explorer 5 or later (Windows or Macintosh); any Mozilla-
based browser (including Firefox, Netscape 7 or later, and Camino); Apple Safari; and Opera 7
or later.
objects
In JavaScript, an object is an unordered collection of key-value pairs. Each key-value pair is
called a property.

The key of a property can be a string. The value of a property can be any value, e.g., a string,
a number, an array, and even a function.

JavaScript provides you with many ways to create an object. The most commonly used one is to
use the object literal notation.

The following example creates an empty object using the object literal notation:

let empty = {};

To create an object with properties, you use the key:value within the curly braces.

For example, the following creates a new person object:

let person = {
firstName: 'John',
lastName: 'Doe'
};

The person object has two properties firstName and lastName with the corresponding
values 'John' and 'Doe'.

When an object has multiple properties, you use a comma (,) to separate them like the above
example.

Accessing object properties

To access a property of an object, you use one of two notations: the dot notation and array-like
notation.

1) The dot notation (.)

The following illustrates how to use the dot notation to access a property of an object:

objectName.propertyName

For example, to access the firstName property of the person object, you use the following
expression:
person.firstName

This example creates a person object and shows the first name and last name to the console:

let person = {

firstName: 'John',

lastName: 'Doe'

};

console.log(person.firstName);

console.log(person.lastName);

2) Array-like notation ( [])

The following illustrates how to access the value of an object’s property via the array-like
nottion:

objectName['propertyName']

Example:

let person = {

firstName: 'John',

lastName: 'Doe'

};

console.log(person['firstName']);

console.log(person['lastName']);
When a property name contains spaces, you need to place it inside quotes. For example, the
following address object has the 'building no' as a property:

let address = {

'building no': 3960,

street: 'North 1st street',

state: 'CA',

country: 'USA'

};

Modifying the value of a property

To change the value of a property, you use the assignment operator (=).

For example:

let person = {

firstName: 'John',

lastName: 'Doe'

};

person.firstName = 'Jane';

console.log(person);

In this example, we changed the value of the firstName property of the person object
from 'John' to 'Jane'.
Adding a new property to an object

Unlike objects in other programming languages such as Java and C#, you can add a property to
an object after object creation.

The following statement adds the age property to the person object and assigns 25 to it:

person.age = 25;

Deleting a property of an object

To delete a property of an object, you use the delete operator:

delete objectName.propertyName;

delete person.age;

Checking if a property exists

To check if a property exists in an object, you use the in operator:

propertyName in objectName

The in operator returns true if the propertyName exists in the objectName.

The following example creates an employee object and uses the in operator to check if
the ssn and employeeId properties exist in the object:

let employee = { firstName: 'Peter', lastName: 'Doe', employeeId: 1};

console.log('ssn' in employee);

console.log('employeeId' in employee);
variables
A JavaScript variable is simply a name of storage location.You can place data into these
containers and then refer to the data simply by naming the container.

Before you use a variable in a JavaScript program, you must declare it. Variables are declared
with the var keyword as follows.

<scripttype="text/javascript">

var money;
var name;
</script>

You can also declare multiple variables with the same var keyword as follows −

<scripttype="text/javascript">

var money, name;


</script>

Storing a value in a variable is called variable initialization. You can do variable initialization

at the time of variable creation or at a later point in time when you need that variable.

JavaScript is untyped language. This means that a JavaScript variable can hold a value of any
data type. Unlike many other languages, you don't have to tell JavaScript during variable
declaration what type of value the variable will hold. The value type of a variable can change
during the execution of a program and JavaScript takes care of it automatically.

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.
Variable Scope

JavaScript variables have only two scopes.

Global Variables − A global variable has global scope which means it can be defined
anywhere in your JavaScript code.A variable i.e. declared outside the function or declared with
window object is known as global variable.

<script>
var data=200;//gloabal variable
function a(){
document.writeln(data);
}
function b(){
document.writeln(data);
}
a();//calling JavaScript function
b();
</script>

Local Variables − A local variable will be visible only within a function where it is defined.
Function parameters are always local to that function.
<script>
function abc(){
var x=10;//local variable
}
</script>
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:

Primitive data types

There are five types of primitive data types in JavaScript. They are as follows:

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

non-primitive data types

Data Type Description

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

There are following types of operators in JavaScript.

1. Arithmetic Operators

Arithmetic operators are used to perform arithmetic operations on the operands. The following
operators are known as JavaScript 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

2. Comparison (Relational) Operators

The JavaScript comparison operator compares the two operands. The comparison operators
are as follows:

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

3. Bitwise Operators

The bitwise operators perform bitwise operations on operands. The bitwise operators are as
follows:

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

4. Logical Operators

The following operators are known as 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


5. Assignment Operators

The following operators are known as JavaScript 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

Making comparisons
Difference between JavaScript and HTML

Parameters of JavaScript HTML


Comparison

Basics It is a scripting language that can be In simple terms, HTML is a


executed on the client-side of a web standardized markup language
browser and was developed by that is used for the purpose of
Netscape. It is a high-level providing the fundamental
programming language. Any web structure of a website.
page may be made more dynamic
and interactive by using this highly
complex programming language,
which can be utilized on any
website.
Usage Provides dynamic features to web Offers material on web sites that
pages that were previously static. is not available for modification
and is known as static.
Community Under ECMA TC-39 Committee. Under W3C and WHATWG.
Compatibility Does not work with several Supports a variety of browsers
browsers at the same time. and operating systems. All
According to the functions, browsers provide their support for
browsers provide support for them it.
Standardization Has been given an official stamp of It has been standardised by
approval by ECMA. organisations such as the W3C
and the WHATWG.
Embedding It is possible for us to include Inside of a JavaScript file, we are
JavaScript into the HTML code in unable to incorporate HTML
the form of a script. code.
Complexity Because it has a greater number of Because it just has the most
interactive elements, it is more fundamental capabilities, it is
difficult to utilise. Spending more extremely easy to comprehend,
time and making more effort is study, and put into practise.
required to learn JavaScript.

Difference between C, C++, Javascript


C C++ Javascript
It is a statictyped It is a statically typed It is a dynamically typed
language. language. language.
It is low level It is considered to be It is a high level programming
programming language. grouped with low level language.
programming language.
C programming language It was created by Bjarne In 1995, JavaScript was
developed by Dennis Stroustrup at bell introduced by Brendan Eich at
Ritchie at Bell laboratories of AT&T in Netscape i.
Laboratories in 1972. 1980.
It is little challenging to It is little challenging to It is little easy to learn for
learn for beginners. learn for beginners. beginners.
C is slower as compared to C++ is more faster as JavaScript is little slower as
C++. compared to JavaScript. compared to C++ programming
language.
It is built for developing Actually it was built for It has been built for web pages.
system softwares everything else than web.
It is a programming It is a programming It is a scripting language.
language. language.
It is compiled and It is compiled and executed. It is compiled language.
executed.
It is an procedure oriented It is an object oriented It is a multiparadigm
programming language. programming language. programming language which
supports event-driven, functional.
Companies using C are Companies using C++ are Companies using JavaScript are
IBM, Apple, Oracle, Google, Lyft, Twitch, Microsoft, Paypal, Netflix,
RedHat etc. coderus etc. Groupon, Uber, Facebook,
Google, etc

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

Some of the HTML events and their event handlers are:

Mouse events:

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.

Keyboard events:

Event Performed Event Handler Description

Keydown & Keyup onkeydown & onkeyup When the user press and then release the key

Form events:
Event Event Description
Performed Handler

focus onfocus When the user focuses on an element

submit onsubmit When the user submits the form

blur onblur When the focus is away from a form element

change onchange When the user modifies or changes the value of a form
element

Window/Document events

Event Event Description


Performed Handler

load onload When the browser finishes the loading of the page

unload onunload When the visitor leaves the current webpage, the browser
unloads it

resize onresize When the visitor resizes the window of the browser

Examples:

 Click Event
<html>

<head> Javascript Events </head>

<body>

<script language="Javascript" type="text/Javascript">

<!--

function clickevent()

document.write("This is JavaTpoint");

//-->

</script>

<form>

<input type="button" onclick="clickevent()" value="Who's this?"/>

</form>

</body>

</html>

 MouseOver Event

<html>
<head>

<h1> Javascript Events </h1>

</head>

<body>

<script language="Javascript" type="text/Javascript">

<!--

function mouseoverevent()

alert("This is JavaTpoint");

//-->

</script>

<p onmouseover="mouseoverevent()"> Keep cursor over me</p>

</body>

</html>

 Focus Event

<html>
<head> Javascript Events</head>

<body>

<h2> Enter something here</h2>

<input type="text" id="input1" onfocus="focusevent()"/>

<script>

<!--

function focusevent()

document.getElementById("input1").style.background=" aqua";

//-->

</script>

</body>

</html>

Keydown Event

<html>
<head> Javascript Events</head>

<body>

<h2> Enter something here</h2>

<input type="text" id="input1" onkeydown="keydownevent()"/>

<script>

<!--

function keydownevent()

document.getElementById("input1");

alert("Pressed a key");

//-->

</script>

</body>

</html>

Load event

<html>
<head>Javascript Events</head>

</br>

<body onload="window.alert('Page successfully loaded');">

<script>

<!--

document.write("The page is loaded successfully");

//-->

</script>

</body>

</html>

Writing your first script


To demonstrate how we’ll use these tools, let’s create a classic ‘‘Hello, World’’ page in three
stages: first as plain HTML, then augmented with JavaScript, and finally styled with CSS.
For the sake of simplicity, the kind of scripts we’re building now are the kind that run
automatically, immediately after the browser loads the HTML page. Although all scripting and
browsing work here is done offline, the behavior of the page is identical if you place the source
file on a server and someone accesses it through the web.
To begin, open your text editor and your browser. Also run Windows File Manager/Macintosh
Finder to create a folder in which to save your scripts.

Stage 1: static HTML


Create a new text file and enter the markup in

Source Code for hello-world.html


<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<title>Hello, World</title>
</head>
<body>
<h1>Hello, World</h1>
<p>This is HTML.</p>
</body>
</html>

Save this file to your hard drive as hello-world.html, and open it in your browser. Figure 3-3
shows the page as it appears in the browser after you’re finished. The precise appearance (or
voice, if you’re using a screen-reader) may vary slightly from one browser to the next, since at
this point we’re relying on the default style sheet in the browser to render the page.
The head of this page contains two required elements: a meta tag that declares the MIME type
and character set, and a title. The body consists of a headline and a paragraph of text, pure and
simple.

Stage 2: connecting with JavaScript


Now let’s add JavaScript to the page. Create a new text file on your computer

Source Code for hello-world.js


var today = new Date();
var msg = "This is JavaScript saying it’s now " + today.toLocaleString();
alert(msg);
The static HTML file displayed in a browser.

Save this file as hello-world.js. It consists of just three JavaScript statements: the first gets the
current date, the second composes a brief message, and the third displays the message.
To enable this JavaScript program to act on your HTML document, add a new script tag to the
head section of the HTML

Revised Source Code for hello-world.html


...
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<title>Hello, World</title>
<script type="text/javascript" src="hello-world.js"></script>
</head>

The HTML script element tells the browser the type and name of the script file to combine with
the document. Because the src (source) attribute doesn’t include a path, the system assumes it’s
in
the same folder as the HTML file. Unlike the meta tag, every <script> tag must be closed with
</script>.
When you save the new JavaScript file and the modified HTML file, reload the HTML file in
your
browser.

A JavaScript alert().
The text we passed to alert() appears in what’s called a modal dialog. ‘‘Modal’’ means that you
can’t do anything more with the application (your browser) until you close the dialog. Notice
that the HTML headline and paragraph seem to have disappeared! No worries; they will appear
as soon as you click OK on the modal dialog. Why? The browser renders the HTML file from
top to bottom. It encounters the script tag in the head and runs the named JavaScript program
before it renders the HTML body. In this case, the modal dialog produced by the alert() method
halts the rendering of the rest of the page until we respond.

Stage 3: styling with CSS


Let’s add some styling to the page so that you can see how HTML and CSS interact. Create a
new text file on your computer

Source Code for hello-world.css


h1
{
font: italic 3em Arial;
}
p
{
margin-left: 2em;
font-size: 1.5em;
}

Save this file to your hard drive as hello-world.css.


This style sheet applies a particular font and color to all the h1 elements on the page, and a left
margin and font-size to all the p elements. Of course, in our document, there is only one of
each.
To enable this style sheet to affect your HTML document, add a link tag to the head section of
the HTML
Revised Source Code for hello-world.html
...
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<title>Hello, World</title>
<script type="text/javascript" src="hello-world.js"></script>
<link type="text/css" rel="stylesheet" href="hello-world.css">
</head>
...

The link element tells the browser the type, relationship, and name of the style sheet to combine
with the document. Note that, like the meta tag and unlike the script tag, link is an ‘‘empty’’ tag
and does not take a separate closing tag. Because the src (source) attribute doesn’t include a
path, the system assumes it’s in the same folder as the HTML file. Every <script> tag must be
closed with </script>.
When you save these files and reload the HTML document in your browser (and click OK on
that modal dialog)
A styled page.
Internal vs. external scripts
JavaScript provides 3 places to put the JavaScript code: within body tag, within head tag and
external JavaScript file.

3 Places to put JavaScript code

1. Between the body tag of html


2. Between the head tag of html
3. In .js file (external javaScript)

1) JavaScript Example : code between the body tag

In the above example, we have displayed the dynamic content using JavaScript. Let’s see the
simple example of JavaScript that displays alert dialog box.

<script type="text/javascript">
alert("Hello Javatpoint");
</script>

2) JavaScript Example : 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.

In this example, we are creating a function msg(). To create function in JavaScript, you need to
write function with function_name as given below.

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" onclick="msg()"/>

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

create an external JavaScript file that prints Hello Javatpoint in a alert dialog box.

message.js

function msg(){
alert("Hello Javatpoint");
}

include the JavaScript file into html page. It calls the JavaScript function on button click.

index.html

<html>
<head>
<script type="text/javascript" src="message.js"></script>
</head>
<body>
<p>Welcome to JavaScript</p>
<form>
<input type="button" value="click" onclick="msg()"/>
</form>
</body>
</html>

Advantages of External JavaScript

There will be following benefits if a user creates an external javascript:

1. It helps in the reusability of code in more than one HTML file.


2. It allows easy code readability.
3. It is time-efficient as web browsers cache the external js files, which further reduces the
page loading time.
4. It enables both web designers and coders to work with html and js files parallelly and
separately, i.e., without facing any code conflictions.
5. The length of the code reduces as only we need to specify the location of the js file.

Disadvantages of External JavaScript

There are the following disadvantages of external files:

1. The stealer may download the coder's code using the url of the js file.
2. If two js files are dependent on one another, then a failure in one file may affect the
execution of the other dependent file.
3. The web browser needs to make an additional http request to get the js code.
4. A tiny to a large change in the js code may cause unexpected results in all its dependent
files.
5. We need to check each file that depends on the commonly created external javascript file.
6. If it is a few lines of code, then better to implement the internal javascript code.
Comments in scripts

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.

Advantages of JavaScript comments

There are mainly two advantages of JavaScript comments.

1. To make code easy to understand It can be used to elaborate the code so that end user
can easily understand the code.
2. To avoid the unnecessary code It can also be used to avoid the code being executed.
Sometimes, we add the code to perform some action. But after sometime, there may be
need to disable the code. In such case, it is better to use comments.

Types of JavaScript Comments

There are two types of comments in JavaScript.

1. Single-line Comment

It is represented by double forward slashes (//). It can be used before and after the statement.

Let’s see the example of single-line comment i.e. added before the statement.

<script>
// It is single line comment
document.write("hello javascript");
</script>

2. Multi-line Comment

It can be used to add single as well as multi line comments. So, it is more convenient.

It is represented by forward slash with asterisk then asterisk with forward slash.
For example:

<script>
/* It is multi line comment.
It will not be displayed */
document.write("example of javascript multiline comment");
</script>

NoScript
The noscript element is the converse of script. A JavaScript-aware browser will render the
contents of the noscript block if scripting has been turned off or if the browser doesn’t support a
scripting language invoked by a script element in the document. (Significantly, a legacy
browser that doesn’t support scripting at all and doesn’t recognize script-related tags will
likewise render the contents of both script and noscript blocks, which is why we comment out
the contents of a script block. A noscript block will therefore be rendered by all browsers when
scripting is not supported.)
You can display any standard HTML within the noscript tag set. It is a block-level element that
can contain paragraphs, lists, divisions, headings, and so on.
The conventional use of noscript is to present HTML content to display in the absence of
scripting support — a message such as, ‘‘This page would be more interesting if viewed with
JavaScript running,’’ for example, or an HTML hyperlink to a page that provides content that
would otherwise be inserted by Javascript.

Example:
<script>
document.write("Welcome to JavaTpoint")
</script>
<noscript>Sorry! Your browser does not support JavaScript.!</noscript>
alert dialogs

The alert() method in JavaScript is used to display a virtual alert box. It is mostly used to give a
warning message to the users. It displays an alert dialog box that consists of some specified
message (which is optional) and an OK button. When the dialog box pops up, we have to click
"OK" to proceed.

The alert dialog box takes the focus and forces the user to read the specified message. So, we
should avoid overusing this method because it stops the user from accessing the other parts of
the webpage until the box is closed.

Rather than showing the warnings or errors, the alert dialog box can be used for normal
messages such as 'welcome back', 'Hello XYZ', etc.

Syntax:

alert(message)

Values:

message: It is an optional string that specifies the text to display in the alert box. It consists of
the information that we want to show to the users.

<html>
<head>
<script type = "text/javascript">
function fun() {

alert ("This is an alert dialog box");


}
</script>
</head>
<body>
<p> Click the following button to see the effect </p>
<form>
<input type = "button" value = "Click me" onclick = "fun();" />
</form>
</body>
</html>
Conditional statements
JavaScript supports conditional statements which are used to perform different actions based on
different conditions.

There are three forms of if statement in JavaScript.

JavaScript If statement

It evaluates the content only if expression is true. The signature of JavaScript if statement is
given below.

Syntax:

if(expression){
//content to be evaluated
}

Flowchart of JavaScript If statement


Example:

<script>
var a=20;
if(a>10){
document.write("value of a is greater than 10");
}
</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.

Syntax:

if(expression){
//content to be evaluated if condition is true
}
else{
//content to be evaluated if condition is false
}
Flowchart of JavaScript If...else statement

Let’s see the example of if-else statement in JavaScript to find out the even or odd number.

<script>
var a=20;
if(a%2==0){
document.write("a is even number");
}
else{
document.write("a is odd number");
}
</script>
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.

Syntax:

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>
Flowchart of JavaScript If...else .. if statement
Getting confirmations from users

JavaScript confirm method invokes a function that asks the user for a confirmation dialogue on
a particular action. The confirm () method uses a window object to invoke a dialogue with a
question and two option buttons, OK and Cancel. If the user selects the OK option, it will
continue to the function execution; selecting the Cancel option will abort the block code's
execution.

It returns true if the user selects the OK option; otherwise, it returns false.

Syntax:

confirm("Select an Option!");

Parameters:

It takes a "message" value in string format to display in the confirmation dialogue you want to
show the user.

Return value:

The confirm method returns a Boolean output, either true or false, if the OK is selected.

A boolean indicating whether OK (true) or Cancel (false) was selected. If a browser ignores in-
page dialogues, then the returned value is always false.

Usage of the Confirm method

o The JavaScript confirm() method is used to display a specific message on a dialogue


window with the OK and Cancel options to confirm the user action.
o For dealing with some CRUD operations, it is necessary to use a confirmation message
instead of directly applying an action.
o It is used to accept or verify something.
o It forces the browser to read the message and focus on the current window.
o It stops all the actions until the confirmation window is closed.
o It returns true when users select OK and false on the selection of the CANCEL option.
Example:

<!DOCTYPE html>

<html>

<head>

</head>

<body>

<p>Click the button to invoke the confirm().</p>

<button onclick="myFunction()">Click Here</button>

<p id="conf"></p>

<script>

function myFunction() {

var result;

var r = confirm("Select an Action!");

if (r == true) {

result = "You have selected OK!";

} else {

result = "You have selected Cancelled!";

document.getElementById("conf").innerHTML = result;

</script>

</body>

</html>
Creating prompts for users

The prompt() method in JavaScript is used to display a prompt box that prompts the user for
the input. It is generally used to take the input from the user before entering the page. It can be
written without using the window prefix. When the prompt box pops up, we have to click "OK"
or "Cancel" to proceed.

The box is displayed using the prompt() method, which takes two arguments: The first
argument is the label which displays in the text box, and the second argument is the default
string, which displays in the textbox. The prompt box consists of two buttons, OK and Cancel.
It returns null or the string entered by the user. When the user clicks "OK," the box returns the
input value. Otherwise, it returns null on clicking "Cancel".

The prompt box takes the focus and forces the user to read the specified message. So, it should
avoid overusing this method because it stops the user from accessing the other parts of the
webpage until the box is closed.

Syntax:

prompt(message, default)

Values

The parameter values of this function are defined as follows.

message: It is an optional parameter. It is the text displays to the user. We can omit this value if
we don't require to show anything in the prompt.

default: It is also an optional parameter. It is a string that contains the default value displayed in
the textbox.

Let's see some examples of the JavaScript prompt() method.


Example

In this example, there is a simple prompt box with a message and two buttons (OK and Cancel).
Here, there is an HTML button which is used for displaying the prompt box. We are using the
onclick attribute and call the fun() function where the prompt() is defined.

<html>

<head>

<script type = "text/javascript">

function fun() {

prompt ("This is a prompt box", "Hello world");

</script>

</head>

<body>

<p> Click the following button to see the effect </p>

<form>

<input type = "button" value = "Click me" onclick = "fun();" />

</form>

</body>

</html>
Understanding functions

JavaScript functions are used to perform operations. We can call JavaScript function many
times to reuse the code. Before we use a function, we need to define it. The most common way
to define a function in JavaScript is by using the function keyword, followed by a unique
function name, a list of parameters (that might be empty), and a statement block surrounded by
curly braces.

Advantage of JavaScript function

There are mainly two advantages of JavaScript functions.

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

The syntax of declaring function is given below.

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


//code to be executed
}

JavaScript Function Example

Let’s see the simple example of function in JavaScript that does not has arguments.

<html>

<head>

<script type = "text/javascript">

function sayHello() {

document.write ("Hello there!");

}
</script>

</head>

<body>

<p>Click the following button to call the function</p>

<form>

<input type = "button" onclick = "sayHello()" value = "Say Hello">

</form>

<p>Use different text in write method and then try...</p>

</body>

</html>

JavaScript Function Arguments

We can call function by passing arguments. These passed parameters can be captured inside the
function and any manipulation can be done over those parameters. A function can take multiple
parameters separated by comma. Let’s see the example of function that has one argument.

<html>

<head>

<script type = "text/javascript">

function sayHello(name, age) {

document.write (name + " is " + age + " years old.");

</script>

</head>

<body>
<p>Click the following button to call the function</p>

<form>

<input type = "button" onclick = "sayHello('Zara', 7)" value = "Say Hello">

</form>

<p>Use different parameters inside the function and then try...</p>

</body>

</html>

The return Statement

A JavaScript function can have an optional return statement. This is required if you want to
return a value from a function. This statement should be the last statement in a function.

For example, you can pass two numbers in a function and then you can expect the function to
return their multiplication in your calling program.

Example

Try the following example. It defines a function that takes two parameters and concatenates
them before returning the resultant in the calling program.

<html>

<head>

<script type = "text/javascript">

function concatenate(first, last) {

var full;

full = first + last;

return full;

function secondFunction() {
var result;

result = concatenate('Zara', 'Ali');

document.write (result );

</script>

</head>

<body>

<p>Click the following button to call the function</p>

<form>

<input type = "button" onclick = "secondFunction()" value = "Call Function">

</form>

<p>Use different parameters inside the function and then try...</p>

</body>

</html>
Making links smarter
Using switch/case statements
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

Synatax:

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>
Handling errors

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.

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.

Error Object

When a runtime error occurs, it creates and throws an Error object. Such an object can be used
as a base for the user-defined exceptions too. An error object has two properties:

1. name: This is an object property that sets or returns an error name.


2. message: This property returns an error message in the string form.

JavaScript is a loosely-typed language. It does not give compile-time errors. So some times you
will get a runtime error for accessing an undefined variable or calling undefined function etc.

JavaScript provides error-handling mechanism to catch runtime errors using try-catch-finally


block, similar to other languages like Java or C#. try catch block does not handle syntax errors.
Syntax:

try
{
// code that may throw an error
}
catch(ex)
{
// code to be executed if an error occurs
}
finally{
// code to be executed regardless of an error occurs or not
}

try:

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.

wrap suspicious code that may throw an error in try block.

catch:

write code to do something in catch block when an error occurs. The catch block can have
parameters that will give you error information. Generally catch block is used to log an error or
display specific messages to the user.

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.
finally:

code in the finally block will always be executed regardless of the occurrence of an error. The
finally block can be used to complete the remaining task or reset variables that might have
changed before error occurred in try block.

Example: Error Handling in JS

<!DOCTYPE html>
<html>
<body>
<h1>Demo: Error Handling</h1>

<p id="errorMessage"></p>

<script>
try
{
var result = Sum(10, 20); // Sum is not defined yet
}
catch(ex)
{
document.getElementById("errorMessage").innerHTML = ex;
}
</script>
</body>
</html>

In the above example, we are calling function Sum, which is not defined yet. So, try block will
throw an error which will be handled by catch block. Ex includes error message that can be
displayed.
The finally block executes regardless of whatever happens.

Example: finally Block

<!DOCTYPE html>
<html>
<body>
<h1>Demo: Error Handling</h1>

<p id="errorMessage">Error: </p>


<p id="message"></p>

<script>
try
{
var result = Sum(10, 20); // Sum is not defined yet
}
catch(ex)
{
document.getElementById("errorMessage").innerHTML += ex;
}
finally{
document.getElementById("message").innerHTML = "finally block
executed";
}

</script>
</body>
</html>

Although Error is a generic constructor, there are following standard built-in error types or error
constructors beside it:
1. 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.
2. InternalError: It creates an instance when the js engine throws an internal error.
3. RangeError: It creates an instance for the error that occurs when a numeric variable or
parameter is out of its valid range.
4. ReferenceError: It creates an instance for the error that occurs when an invalid
reference is de-referenced.
5. SyntaxError: An instance is created for the syntax error that may occur while parsing
the eval().
6. TypeError: When a variable is not a valid type, an instance is created for such an error.
7. URIError: An instance is created for the error that occurs when invalid parameters are
passed in encodeURI() or decodeURI().

You might also like