[Go to site: main page, start]

0% found this document useful (0 votes)
13 views111 pages

Introduction to JavaScript Basics

JavaScript is a widely-used client-side scripting language for creating dynamic web pages, initially named LiveScript before being renamed by Netscape. It allows interaction with HTML elements, client-side validation, and asynchronous data loading, among other functionalities. The document also covers JavaScript syntax, data types, variable declaration, functions, and the use of comments.

Uploaded by

ppriyakansara10
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)
13 views111 pages

Introduction to JavaScript Basics

JavaScript is a widely-used client-side scripting language for creating dynamic web pages, initially named LiveScript before being renamed by Netscape. It allows interaction with HTML elements, client-side validation, and asynchronous data loading, among other functionalities. The document also covers JavaScript syntax, data types, variable declaration, functions, and the use of comments.

Uploaded by

ppriyakansara10
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

Unit 3.

Java Script

JavaScript is an object-based client-side scripting language that is very popular and used to create
dynamic and interactive web pages. Javascript is an interpreted language usually used with HTML,
and programs written in JavaScript are called lightweight scripts.

Earlier, JavaScript was named LiveScript, but later, Netscape changed its name to JavaScript because
its origin was from Java which was very popular at that time. JavaScript released its first look
for Netscape 2.0 in 1995 under the name "LiveScript".

Where Is JavaScript Being Used?

 JavaScript can interact with HTML DOM elements and dynamically control the webpage.
 You can perform client-side validation using Javascript.
 Using JavaScript, you can create drop-down menus, pop-up windows, and dialog boxes.
 JavaScript can be used to load asynchronous data without refreshing the webpage.
 JavaScript can be used in game development.

Advantages of JavaScript

 Speed: JavaScript is a client-side scripting language. It is very fast because all its code
functions run immediately on the client machine instead of contacting the server and waiting
for a response.
 Simplicity: JavaScript is relatively easy to learn and code.
 Versatility: JavaScript works well with other languages and is also used in various
applications.
 Server Load: Being on the client-side reduces the requirement on the website server.

What Does the Script Mean?

A script is a set of instructions given in the form of code. Instructions are designed for either the web
browser (client-side scripting) or the server (server-side scripting). Scripts provide changes to the web
page.
3.2 Internal and External Java Script

Inserting JavaScript into a webpage is much like inserting any other HTML content. The tags used
to add JavaScript in HTML are <script> and </script>. The code surrounded by the <script> and
</script> tags is called a script blog.
‘type’ attribute was the most important attribute of <script> tag. However, it is no longer used.
Browser understands that <script> tag has JavaScript code inside it.

<script></script>

Internal javaScript

 Create an html file(.htm) extension and write javascript code inside the ‘script’ tag
 then simply load the HTML file in the browser

External javaScript

 Create a separate javascript file(.js) with .js extension. Write your code in it.
 Now link this js file with the HTML document using script tag like:

<script src='relative_path_to_file/file_name.js'></script>
 either in the body or in the head.

Printing Hello World in JavaScript


Whenever we write javascript we make use of the ‘script’ tag. We know what a normal HTML
document is made up of. The ‘script’ tag is used to write javascript code and this ‘script’ tag is
either placed inside the ‘head’ tag or inside the ‘body’ tag.

<!DOCTYPE HTML>

<html>

<head>

<title></title>

<!-- Script tag can also be placed here -->

</head>
<body>

<p>Before the script...</p>

<!-- Script tag inside the body -->

<script>

// write the javascript code inside it

</script>

<p>...After the script.</p>

</body>

</html>

We can put the script tag inside the ‘head’ or ‘body’ tag. Though it should be noted that each
choice of putting the ‘script’ tag has its own consequences. For now, you can put the script tag
anywhere you want.
Printing Hello World
In order to print the famous ‘Hello World’ sentence to the screen, we can make use of different
methods that javascript provides. Most common are:
 [Link]()
 [Link]()
 alert()
Each of the above method have different ways of outputting the content. Though
‘[Link]()’ is used when we want to print the content onto the document which is the
HTML Document. Also ‘[Link]()’ is mainly used when we are debugging javascript code
and same thing with ‘alert()’.
Example:

<script>
// using [Link]
[Link]('Hello World');
</script>

Hit Ctrl+Shift+J to see the output in the browser console. Or press f12 key.

[Link]
<script>
// using [Link]
[Link]('Hello World');
</script>

Alert

<script>
// using alert
alert('Hello World');
</script>

3.3 Data types and Variables


Data Types − Every variable in JavaScript has a data type that defines the type of variable it is and
what kind of data is being stored in the variable. There are two types of data types that are available in
JavaScript namely Primitive Data Types and Non-Primitive Data Types.

Primitive Data Types − This is the predefined data type that is provided by JavaScript for different
usages. These are also known as the in-built data types.

Primitive Datatypes
Different types of Primitive Datatype are −
[Link] −This data type can hold the decimal values as well as the without decimal values in
JavaScript.
Example 1
In the below example, we will be exploring the Number data type.
<html>

<head>

<title>Data Types</title>

</head>

<body>

<script>

var x = 3874772;

var y = 22/7;

[Link]("Value of x: " + x +"<br>");

[Link]("Value of y: " + y+"<br>");

</script>

</body>

</html>

Output:

Value of x: 3874772
Value of y: 3.142857142857143

2. String Datatype − The String datatype in JavaScript is used for representing a sequence of
characters that is surrounded by single or double quotes.

<html>

<head>

<title>Data Types</title>

</head>

<body>

<script>

var str = 'Hello User...';


var str1 = "Welcome to Tutorials Point";

[Link]("String: " + str+"<br>");

[Link]("String 1: " + str1+"<br>");<

</script>

</body>

</html>

Output:

String: Hello User...


String 1: Welcome to Tutorials Point

3. Undefined − The undefined data type is used when the value of any request or response cannot be
defined by JavaScript. For example: Initializing a number without value.

<html>

<head>

<title>Data Types</title>

</head>

<body>

<script>

let x;

[Link]("Value of x: " + x +"<br>");

x = undefined

[Link]("x: " + x +"<br>");

</script>

</body>

</html>
Output
Value of x: undefined
x: undefined

3. Boolean − The boolean data type only accepts two types of values i.e. either true or false.

<script>
let x = 5;
let y = 5;
let z = 6;

[Link]("demo").innerHTML =
(x == y) + "<br>" + (x == z);
</script>

5. Null − This only accepts null values.

Non-primitive datatypes
The non-primitive data types are as follows −
1. Object − The objects in JavaScript are entities that have properties and methods. Everything in
Java is an Object.

JavaScript objects are written with curly braces {}.

Object properties are written as

Property name:value pairs, separated by commas.

Creating an Object in JavaScript


Defining an Object using constructor:
// Create an empty generic object
var obj = new Object();

//Create a user defined object


var mycar = new Car();
Defining an Object using literal annotations −
// An empty object
var square = {};

// Here a and b are keys and


// 20 and 30 are values
var circle = {a: 20, b: 30};

<html>

<head>

<title>Data Types</title>

</head>

<body>

<script>

// Creating object with the name person

let student = {

firstName: "Gary",

lastName: "Phillips",

};

// Printing the value on console

[Link]("Full Name: " + [Link] + " " + [Link]);

</script>

</body>

</html>

Output:

Full Name: Gary Phillips

Example:
<p id="demo"></p>

<script>
const person = {
firstName : "John",
lastName : "Doe",
age : 50,
eyeColor : "blue"
};
[Link]("demo").innerHTML =
[Link] + " is " + [Link] + " years old.";
</script>

2. Array − Arrays in JavaScript can be used for storing more than one element under a single name.

JavaScript arrays are written with square brackets.

Array items are separated by commas.

Array indexes are zero-based, which means the first item is [0], second is [1], and so on.

Declaring a 1D array −
// Call it with no arguments
var a = new Array();

// Call it with single numeric argument


var b = new Array(10);

// Explicitly specify two or


// more array elements
var d = new Array(1, 2, 3, "Hello");

Example 6
# [Link]
<html><head>
<title>Data Types</title></head><body>
<h1 style="color: red;">
Welcome To Tutorials Point
</h1>
<script>
var x = new Array();
var y = new Array(21);
var z = new Array("Hello", 21, "Tutorials", "Point", 32, 56);
[Link]("value of x: " + x);
[Link]("value of y: " + y);
[Link]("value of z: " + z);
</script></body></html>

Output
The above program will produce the following output in the Console.
value of x:
value of y: ,,,,,,,,,,,,,,,,,,,,
value of z: Hello,21,Tutorials,Point,32,56

Example:

<p id="demo"></p>

<script>

var cars = ["aab","Volvo","BMW"];

[Link]("demo").innerHTML = cars[0];

</script>

[Link]
A JavaScript function is a block of code designed to perform a particular task.
<p id="demo"></p>

<script>

function myFunction(p1, p2) {

return p1 * p2;

[Link]("demo").innerHTML = myFunction(4, 3);

</script>

Function Syntax
A JavaScript function is defined with the function keyword, followed by a name, followed by parentheses ().

Function names can contain letters, digits, underscores, and dollar signs (same rules as variables).

The parentheses may include parameter names separated by commas:


(parameter1, parameter2, ...)

The code to be executed, by the function, is placed inside curly brackets: {}

JavaScript Variable:

4 Ways to Declare a JavaScript Variable:


 Using var
 Using let
 Using const
 Using nothing

What are Variables?


Variables are containers for storing data (storing data values).

In this example, x, y, and z, are variables, declared with the var keyword:

<p id="demo"></p>

<script>
var x = 5;

var y = 6;

var z = x + y;

[Link]("demo").innerHTML =

"The value of z is: " + z;

</script>

or

let x = 5;

let y = 6;

let z = x + y;

Or

x = 5;
y = 6;
z = x + y;

From all the examples above, you can guess:

 x stores the value 5


 y stores the value 6
 z stores the value 11

When to Use JavaScript var?


Always declare JavaScript variables with var,let, orconst.

The var keyword is used in all JavaScript code from 1995 to 2015.

The let and const keywords were added to JavaScript in 2015.

If you want your code to run in older browser, you must use var.

When to Use JavaScript const?


If you want a general rule: always declare variables with const.

If you think the value of the variable can change, use let.

In this example, price1, price2, and total, are variables:


<p id="demo"></p>

<script>

const price1 = 5;

const price2 = 6;

let total = price1 + price2;

[Link]("demo").innerHTML =

"The total is: " + total;

</script>

The two variables price1 and price2 are declared with the const keyword.

These are constant values and cannot be changed.

The variable total is declared with the let keyword.

This is a value that can be changed.

JavaScript Identifiers
All JavaScript variables must be identified with unique names.

These unique names are called identifiers.

Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume).

The general rules for constructing names for variables (unique identifiers) are:

 Names can contain letters, digits, underscores, and dollar signs.


 Names must begin with a letter
 Names can also begin with $ and _ (but we will not use it in this tutorial)
 Names are case sensitive (y and Y are different variables)
 Reserved words (like JavaScript keywords) cannot be used as names

JavaScript Variable Scope


The scope of a variable is the region of your program in which it is defined. 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.


Local Variables − A local variable will be visible only within a function where it is defined.
Function parameters are always local to that function.

Within the body of a function, a local variable takes precedence over a global variable with the same
name. If you declare a local variable or function parameter with the same name as a global variable,
you effectively hide the global variable. Take a look into the following example.
<html>

<body >

<script type = "text/javascript">

<!--

var myVar = "global"; // Declare a global variable

function checkscope( ) {

var myVar = "local"; // Declare a local variable

[Link](myVar);

//-->

</script>

</body>

</html>

Comments
JavaScript comments can be used to explain JavaScript code, and to make it more readable.

JavaScript comments can also be used to prevent execution, when testing alternative code.

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

This example uses a single-line comment before each code line:


<!DOCTYPE html>

<html>

<body>

<h1 id="myH"></h1>

<p id="myP"></p>

<script>

// Change heading:

[Link]("myH").innerHTML = "JavaScript Comments";

// Change paragraph:

[Link]("myP").innerHTML = "My first paragraph.";

</script>

</body>

</html>

Multi-line Comments
Multi-line comments start with /* and end with */.

Any text between /* and */ will be ignored by JavaScript.

This example uses a multi-line comment (a comment block) to explain the code:

<!DOCTYPE html>

<html>

<body>

<h1 id="myH"></h1>

<p id="myP"></p>

<script>

/*

The code below will change

the heading with id = "myH"


and the paragraph with id = "myP"

*/

[Link]("myH").innerHTML = "JavaScript Comments";

[Link]("myP").innerHTML = "My first paragraph.";

</script>

</body>

</html>

const Keyword
JavaScript const keyword is used to define constant values that can not changed once a value is set. The
value of a constant can't be changed through reassignment, and it can't be redeclared.

The scope of const is block-scoped it means it can not be accessed from outside of block. In case of
scope, it is much like variables defined using the let statement.

Constants can be either global or local to the block in which it is declared. Global constants do not
become properties of the window object, unlike var variables.

JavaScript const Keyword: Syntax


Below we have the syntax to define a constant value in JavaScript.

const name1 = value1 [, name2 = value2 [, ... [, nameN = valueN]]]

Copy

We don't have to use var or let keyword while using the const keyword. Also, we can define a list or a
simple value or a string etc as a constant.

JavaScript const Keyword Example


Lets understand, how to create constant in JavaScript program. See the below example:

const Pi = 3.14;

alert(Pi);

}
Output:

3.14

<!doctype html>

<head>

<style>

/* CSS comes here */

</style>

<title>const Statement</title>

</head>

<body>

<h2>Understand use of const in JavaScript</h2>

<script>

// global scope

const x = 200;

// block scope

const x = 10;

[Link]("Inside the block:"+x);

// function scope

function show() {

const x = 20;

[Link]("<br>Inside the function:"+x);

show();
[Link]("<br>Global x:"+x);

x = 100 // TypeError: Assignment to constant variable.

[Link]("<br>Global x:"+x);

</script>

</body>

</html>

Output:

Understand use of const in JavaScript


Inside the block:10
Inside the function:20
Global x:200

JavaScript Operators
Operators (Arithmetic, Assignment, Comparison, Logical and Conditional Operator)

JavaScript Arithmetic Operators


Arithmetic operators are used to perform arithmetic on numbers:

Operator Description

+ Addition

- Subtraction

* Multiplication

** Exponentiation (ES2016)

/ Division

% Modulus (Division Remainder)


++ Increment

-- Decrement

Arithmetic Operations
A typical arithmetic operation operates on two numbers.

The two numbers can be literals:

<p id="demo"></p>

<script>

let x = 100 + 50;

[Link]("demo").innerHTML = x;

</script>

Or

<p id="demo"></p>

<script>

let a = 100;

let b = 50;

let x = a + b;

[Link]("demo").innerHTML = x;

</script>

Or

<p id="demo"></p>

<script>

let a = 3;

let x = (100 + 50) * a;

[Link]("demo").innerHTML = x;

</script>
Operators and Operands
The numbers (in an arithmetic operation) are called operands.

The operation (to be performed between the two operands) is defined by an operator.

Operand Operator Operand

100 + 50

Adding
The addition operator (+) adds numbers:

<p id="demo"></p>

<script>

let x = 5;

let y = 2;

let z = x + y;

[Link]("demo").innerHTML = z;

</script>

Subtracting
The subtraction operator (-) subtracts numbers.

let x = 5;
let y = 2;
let z = x - y;

Multiplying
The multiplication operator (*) multiplies numbers.

let x = 5;
let y = 2;
let z = x * y;
Dividing
The division operator (/) divides numbers.

let x = 5;
let y = 2;
let z = x / y;

Remainder
The modulus operator (%) returns the division remainder.

let x = 5;
let y = 2;
let z = x % y;

In arithmetic, the division of two integers produces a quotient and a remainder.

In mathematics, the result of a modulo operation is the remainder of an arithmetic division.

Incrementing
The increment operator (++) increments numbers.

let x = 5;
x++;
let z = x;

Decrementing
The decrement operator (--) decrements numbers.

let x = 5;
x--;
let z = x;

Comparison Operators
JavaScript provides comparison operators that compare two operands and return a boolean
value true or false.

Operators Description

== Compares the equality of two operands without considering type.


Operators Description

=== Compares equality of two operands with type.

!= Compares inequality of two operands.

> Returns a boolean value true if the left-side value is greater than the right-side value; otherwise, returns false.

< Returns a boolean value true if the left-side value is less than the right-side value; otherwise, returns false.

>= Returns a boolean value true if the left-side value is greater than or equal to the right-side value; otherwise, returns
false.

<= Returns a boolean value true if the left-side value is less than or equal to the right-side value; otherwise, returns
false.

<!DOCTYPE html>

<html>

<body>

<h1>Demo: JavaScript Comparison Operators</h1>

<p>

var a = 5, b = 10, c = "5", x = a;

</p>

<p id="p1">a == c returns </p>

<p id="p2">a === c returns </p>

<p id="p3">a == x returns </p>

<p id="p4">a != b returns </p>

<p id="p5">a > b returns </p>

<p id="p6">a < b returns </p>

<p id="p7">a >= b returns </p>

<p id="p8">a <= b returns </p>

<script>

var a = 5, b = 10, c = "5", x = a;


[Link]("p1").innerHTML += a == c;

[Link]("p2").innerHTML += a === c;

[Link]("p3").innerHTML += a == x;

[Link]("p4").innerHTML += a != b;

[Link]("p5").innerHTML += a > b;

[Link]("p6").innerHTML += a < b;

[Link]("p7").innerHTML += a >= b;

[Link]("p8").innerHTML += a <= b;

</script>

</body>

</html>

Logical Operators
In JavaScript, the logical operators are used to combine two or more conditions. JavaScript
provides the following logical operators.

Operator Description

&& && is known as AND operator. It checks whether two operands are non-zero or not (0, false, undefined, null or ""
are considered as zero). It returns 1 if they are non-zero; otherwise, returns 0.

|| || is known as OR operator. It checks whether any one of the two operands is non-zero or not (0, false, undefined,
null or "" is considered as zero). It returns 1 if any one of of them is non-zero; otherwise, returns 0.

! ! is known as NOT operator. It reverses the boolean result of the operand (or condition). !false returns true,
and !true returns false.

<!DOCTYPE html>
<html>

<body>

<h1>Demo: JavaScript Logical Operators</h1>

<p id="p1"></p>

<p id="p2"></p>

<p id="p3"></p>

<p id="p4"></p>

<p id="p5"></p>

<script>

var a = 5, b = 10;

[Link]("p1").innerHTML = (a != b) && (a < b);

[Link]("p2").innerHTML = (a > b) || (a == b);

[Link]("p3").innerHTML = (a < b) || (a == b);

[Link]("p4").innerHTML = !(a < b);

[Link]("p5").innerHTML = !(a > b);

</script>

</body>

</html>

Assignment Operators
JavaScript provides the assignment operators to assign values to variables with less key strokes.
Assignment operators Description

= Assigns right operand value to the left operand.

+= Sums up left and right operand values and assigns the result to the left operand.

-= Subtract right operand value from the left operand value and assigns the result to the left operand.

*= Multiply left and right operand values and assigns the result to the left operand.

/= Divide left operand value by right operand value and assign the result to the left operand.

%= Get the modulus of left operand divide by right operand and assign resulted modulus to the left
operand.

<!DOCTYPE html>

<html>

<body>

<h1>Example: JavaScript Assignment Operators</h1>

<p id="p1"></p>

<p id="p2"></p>

<p id="p3"></p>

<p id="p4"></p>

<p id="p5"></p>

<p id="p6"></p>

<script>

var x = 5, y = 10;

x = y;

[Link]("p1").innerHTML = x;

x += 1;

[Link]("p2").innerHTML = x;
x -= 1;

[Link]("p3").innerHTML = x;

x *= 5;

[Link]("p4").innerHTML = x;

x /= 5;

[Link]("p5").innerHTML = x;

x %= 2;

[Link]("p6").innerHTML = x;

</script>

</body>

</html>

Conditional Operator

?: (Conditional operator)
The conditional operator is used as a shortcut for standard if statement. It takes three operands.

Syntax

Condition ? expr1: expr2

Parameters

condition : An expression that evaluates to true or false.

expr1, expr2 : Expressions with values of any types.

If the condition is true, the operator returns the value of expr1; otherwise, it returns the value of
expr2.

For example
status = (marks >= 30) ? "Pass" : "Fail"

The statement assigns value "Pass" to the variable status if marks are 30 or more. Otherwise, it
assigns the value of "Fail" to status.

<!DOCTYPE html>

<html>

<body>

<h1>Demo: JavaScript Ternary Operators</h1>

<p id="p1"></p>

<p id="p2"></p>

<script>

var a = 10, b = 5;

var c = a > b? a : b;

var d = a > b? b : a;

[Link]("p1").innerHTML = c;

[Link]("p2").innerHTML = d;

</script>

</body>

</html>
3.5 Control Structure

conditional statements are used to perform different actions based on various conditions. The
conditional statement evaluates a condition before the execution of instructions.

When you write the code, you require to perform different actions for different decisions. You can
easily perform it by using conditional statements.

Types of Conditional Statements


The conditional statements in JavaScript

are listed below:

o if statement
o if….else statement
o if….else if….statement
o nested if statement
o switch statement

Let us try to elaborate on these conditional statements.


Skip Ad

The if statement
It is one of the simplest decision-making statement which is used to decide whether a block of
JavaScript code will execute if a certain condition is true.

Syntax

1. if (condition) {
2. // block of code will execute if the condition is true
3. }

If the condition evaluates to true, the code within if statement will execute, but if the condition
evaluates to false, then the code after the end of if statement (after the closing of curly braces) will
execute.

Flowchart

For example

1. var x = 78;
2. if (x>70) {

3. [Link]("x is greater")

4. }

Output

x is greater

The if….else statement


An if….else statement includes two blocks that are if block and else block. It is the next form of the
control statement, which allows the execution of JavaScript in a more controlled way. It is used when
you require to check two different conditions and execute a different set of codes. The else
statement is used for specifying the execution of a block of code if the condition is false.

Syntax

1. if (condition)

2. {

3. // block of code will execute if the condition is true

4. }

5. else

6. {

7. // block of code will execute if the condition is false

8. }

If the condition is true, then the statements inside if block will be executed, but if the condition is false,
then the statements of the else block will be executed.

Flowchart
For example

Let us try to understand if….else statement by the following example:

1. var x = 40, y=20;

2. if (x < y)

3. {

4. [Link]("y is greater");

5. }

6. else

7. {

8. [Link]("x is greater");

9. }

Output

x is greater
The if….else if…..else statement
It is used to test multiple conditions. The if statement can have multiple or zero else if statements and
they must be used before using the else statement. You should always be kept in mind that the else
statement must come after the else if statements.

Syntax

1. if (condition1)

2. {

3. // block of code will execute if condition1 is true

4. }

5. else if (condition2)

6. {

7. // block of code will execute if the condition1 is false and condition2 is true

8. }

9. else

10. {

11. // block of code will execute if the condition1 is false and condition2 is false

12. }

Example

1. var a = 10, b = 20, c = 30;


2. if( a > b && a > c) {
3. [Link]("a is greater");
4. } else if( b > a && b > c ) {
5. [Link]("b is greater");
6. } else {
7. [Link]("c is greater");
8. }

Output

c is greater

The nested if statement


It is an if statement inside an if statement.
Syntax

1. if (condition1)
2. {
3. Statement 1; //It will execute when condition1 is true
4. if (condition2)
5. {
6. Statement 2; //It will execute when condition2 is true
7. }
8. else
9. {
10. Statement 3; //It will execute when condition2 is false
11. }
12. }

Example

1. var num = 20;


2. if (num > 10)
3. {
4. if (num%2==0)
5. [Link]( num+ " is greater than 10 and even number");
6. else
7. [Link](num+ " is greater than 10 and odd number");
8. }
9. else
10. {
11. [Link](num+" is smaller than 10");
12. }
13. [Link]("After nested if statement");

Output

20 is greater than 10 and even number


After nested if statement
The switch statement
It is a multi-way branch statement that is also used for decision-making purposes. In some cases,
the switch statement is more convenient than if-else statements. It is mainly used when all branches
depend upon the value of a single variable. It executes a block of code depending upon the different
cases.

The switch statement uses the break or default keywords, but both of them are optional. Let us
define these two keywords:

break: It is used within the switch statement for terminating the sequence of a statement. It is
optional to use. If it gets omitted, then the execution will continue on each statement. When it is used,
then it will stop the execution within the block.

default: It specifies some code to run when there is no case match. There can be only a single default
keyword in a switch. It is also optional, but it is recommended to use it as it takes care of unexpected
cases.

If the condition passed to switch doesn't match with any value in cases, then the statement under the
default will get executed.

Some points to remember

o There can be one or multiple case values for a switch expression.


o The use of break and default keywords are optional.
o The case statements can only include constants and literals. It cannot be an expression or a
variable.
o Unless you put a break after the code of every block, the execution will continuously flow into
the next block.
o It is not necessary that the default case has to be placed at last in a switch block.

Syntax

1. switch(expression){
2. case value1:
3. //code to be executed;
4. break; //optional
5. case value2:
6. //code to be executed;
7. break; //optional
8. ......
9.
10. default:
11. code to be executed if all cases are not matched;
12. }

Flowchart

Example
1. var num = 5;
2. switch(num) {
3. case 0 : {
4. [Link]("Sunday");
5. break;
6. }
7. case 1 : {
8. [Link]("Monday");
9. break;
10. }
11. case 2 : {
12. [Link]("Tuesday");
13. break;
14. }
15. case 3 : {
16. [Link]("Wednesday");
17. break;
18. }
19. case 4 : {
20. [Link]("Thursday");
21. break;
22. }
23. case 5 : {
24. [Link]("Friday");
25. break;
26. }
27. case 6 : {
28. [Link]("Saturday");
29. break;
30. }
31. default: {
32. [Link]("Invalid choice");
33. break;
34. }
35. }

Output

Friday

4. For Loop

 For loop is a compact form of looping.

It includes three important parts:


1. Loop Initialization
2. Test Condition
3. Iteration

 All these three parts come in a single line separated by semicolons(;).


Flow Diagram of 'For' Loop

Syntax

for(initialization; test-condition; increment/decrement)


{
//Statements;
}

Example : Palindrome Program using For Loop

<html>
<body>
<script type="text/javascript">
function palindrome()
{
var revstr = " ";
var strr = [Link]("strr").value;
var i = [Link];
for(var j=i; j>=0; j--)
{
revstr = revstr+[Link](j);
}
if(strr == revstr)
{
alert(strr+" - is Palindrome");
}
else
{
alert(strr+" - is not a Palindrome");
}
}
</script>
<form>
Enter a String or Number: <input type="text" id="strr" name="checkpalindrome"><br>
<input type="submit" value="Check" > </form>
</body>
</html>

Output:
Example:
<!DOCTYPE html>
<html>
<body>
<script>
for (i=1; i<=5; i++)
{
[Link](i + "<br/>")
}
</script>
</body>
</html>

Example

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript For Loop</h2>

<p id="demo"></p>

<script>
const cars = ["BMW", "Volvo", "Saab", "Ford", "Fiat", "Audi"];
let text = "";
for (let i = 0; i < [Link]; i++) {
text += cars[i] + "<br>";
}

[Link]("demo").innerHTML = text;
</script>

</body>
</html>

5. While Loop

 While loop is an entry-controlled loop statement.


 It is the most basic loop in JavaScript.
 It executes a statement repeatedly as long as expression is true.
 Once the expression becomes false, the loop terminates.
Flow Diagram of While Loop

Syntax

while (condition)
{
//Statements;
}

Example : Fibonacci Series Program using While Loop

<html>
<body>
<script type="text/javascript">
var no1=0,no2=1,no3=0;
[Link]("Fibonacci Series:"+"<br>");
while (no2<=10)
{
no3 = no1+no2;
no1 = no2;
no2 = no3;
[Link](no3+"<br>");
}
</script>
</body>
</html>

Output:

Example:

<!DOCTYPE html>
<html>
<body>
<script>
var i=11;
while (i<=15)
{
[Link](i + "<br/>");
i++;
}
</script>
</body>
</html>

7. Do-While Loop

 Do-While loop is an exit-controlled loop statement.


 Similar to the While loop, the only difference is condition will be checked at the end of the loop.
 The loop is executed at least once, even if the condition is false.
Flow Diagram of Do – While

Syntax

do
{
//Statements;
}
while(condition);

Example : Simple Program on Do-While Loop

<html>
<body>
<script type ="text/javascript">
var i = 0;
do
{
[Link](i+"<br>")
i++;
}
while (i <= 5)
</script>
</body>
</html>

Output:
0
1
2
3
4
5

Difference between While Loop and Do – While Loop

While Loop Do – While Loop

In while loop, first it checks the condition and then executes the In Do – While loop, first it executes the program and then check
program. condition.

It is an entry – controlled loop. It is an exit – controlled loop.

The condition will come before the body. The condition will come after the body.

If the condition is false, then it terminates the loop. It runs at least once, even though the conditional is false.

It is a counter-controlled loop. It is a iterative control loop.

8. Break Statement

 Break statement is used to jump out of a loop.


 It is used to exit a loop early, breaking out of the enclosing curly braces.
Syntax:
break;
Flow Diagram of Break Statement

9. Continue Statement

 Continue statement causes the loop to continue with the next iteration.
 It skips the remaining code block.

3.6.3 Javascript Events :


When the page loads, it is called an event. When the user clicks a button, that click too is an event.
Other examples include events like pressing any key, closing a window, resizing a window, etc.
Developers can use these events to execute JavaScript coded responses, which cause buttons to close
windows, messages to be displayed to users, data to be validated, and virtually any other type of
response imaginable.
Events are a part of the Document Object Model (DOM) Level 3 and every HTML element contains a
set of events which can trigger JavaScript Code.

[Link] Mouse Events : (click, mouseover, mouseremove,


mouseout, mouseup)

onclick Event Type


This is the most frequently used event type which occurs when a user clicks the left button of his
mouse. You can put your validation, warning etc., against this event type.
Example
<html>

<head>

<script type = "text/javascript">

<!--

function sayHello() {

alert("Hello World")

//-->

</script>

</head>

<body>

<p>Click the following button and see result</p>

<form>

<input type = "button" value = "Say Hello" />

</form>

</body></html>

onmouseover and onmouseout


These two event types will help you create nice effects with images or even with text as well.
The onmouseover event triggers when you bring your mouse over any element and
the onmouseout triggers when you move your mouse out from that element. Try the following
example.

<!DOCTYPE html>
<html>
<body>

<p>This example demonstrates how to assign an "onmouseover" and


"onmouseout" event to a h1 element.</p>

<h1 id="demo" >
over me</h1>

<script>
function mouseOver() {
[Link]("demo").[Link] = "red";
}

function mouseOut() {
[Link]("demo").[Link] = "pink";
}
</script>

</body>
</html>
Mouseup,mousedown:
The onmousedown event occurs when a user presses a mouse button over an element.

The onmouseup event occurs when a user releases a mouse button over an element.

<!DOCTYPE html>
<html>
<body>

<p id="myP" >
>Click the text! The mouseDown() function is triggered when the
mouse button is pressed down over this paragraph, and sets the color
of the text to red. The mouseUp() function is triggered when the
mouse button is released, and sets the color of the text to green.
</p>

<script>
function mouseDown() {
[Link]("myP").[Link] = "red";
}

function mouseUp() {
[Link]("myP").[Link] = "green";
}
</script>

</body>
</html>
3.6.2 Form Event : (focus, submit, blur, change)

Attribute Description

onblur Some form validation object loos the focus, then event fired.

onchange The value change in the form, then event fired.

onfocus In the form <input>, <a> , <select> object has focus. Working on
this object then event fired.

Onsubmit When the user submits the form

On Blur:-
Definition and Usage
The onblur attribute fires the moment that the element loses focus.

Onblur is most often used with form validation code (e.g. when the user leaves a form
field).

Tip: The onblur attribute is the opposite of the onfocus attribute.

<html>

<body>

Enter your name: <input type="text" name="fname" id="fname" >

<p>When you leave the input field, a function is triggered which transforms the input text to upper case.</p>

<script>

function myFunction() {

var x = [Link]("fname");

[Link] = [Link]();

</script>
</body>

</html>

Eg:2

<html>

<body>

<p>When you enter the input field, a function is triggered which sets the background color to yellow. When you
leave the input field, a function is triggered which sets the background color to red.</p>

Enter your name: <input type="text" id="myInput" >

<script>

// Focus = Changes the background color of input to yellow

function focusFunction() {

[Link]("myInput").[Link] = "yellow";

// No focus = Changes the background color of input to red

function blurFunction() {

[Link]("myInput").[Link] = "red";

</script>

</body>

</html>

onchange:
The onchange attribute fires the moment when the value of the element is changed.

Tip: This event is similar to the oninput event. The difference is that the oninput event
occurs immediately after the value of an element has changed, while onchange occurs
when the element loses focus. The other difference is that the onchange event also works
on <select> elements.
Supported HTML <input type="checkbox">, <input type="file">, <input
tags: type="password">, <input type="radio">, <input
type="range">, <input type="search">, <input type="text">,
<select> and <textarea>

<html>
<body>

<p>Select a new car from the list.</p>

<select id="mySelect" >
<option value="Audi">Audi
<option value="BMW">BMW
<option value="Mercedes">Mercedes
<option value="Volvo">Volvo
</select>

<p>When you select a new car, a function is triggered which outputs the value of the
selected car.</p>

<p id="demo"></p>

<script>
function myFunction() {
var x = [Link]("mySelect").value;
[Link]("demo").innerHTML = "You selected: " + x;
}
</script>

</body>
</html>

Eg:2
<html>
<body>

<p>Modify the text in the input field, then click outside the field to fire the onchange
event.</p>

Enter some text: <input type="text" name="txt" value="Hello"


>

<script>
function myFunction(val) {
alert("The input value has changed. The new value is: " + val);
}
</script>

</body>
</html>

onfocus:

Definition and Usage


The onfocus attribute fires the moment that the element gets focus.

Onfocus is most often used with <input>, <select>, and <a>.

Tip: The onfocus attribute is the opposite of the onblur attribute.

<html>
<body>

<p>A function is triggered when one of the input fields get focus. The function changes the
background-color of the input field.</p>
First name: <input type="text" id="fname" >Last name: <input type="text" id="lname" >

<script>
function myFunction(x) {
[Link](x).[Link] = "yellow";
}
</script>

</body>
</html>

HTML onsubmit Event Attribute


Definition and Usage
The onsubmit attribute fires when a form is submitted.

<html>

<body>

<p>When you submit the form, a function is triggered which alerts some text.</p>

<form action="/action_page.php" >

Enter name: <input type="text" name="fname">

<input type="submit" value="Submit">

</form>

<script>

function myFunction() {

alert("The form was submitted");

</script>

</body>

</html>

More Java Script Examples

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.

JavaScript Form Validation Example


In this example, we are going to validate the name and password. The name can’t be empty
and password can’t be less than 6 characters long.

Here, we are validating the form on form submit. The user will not be forwarded to the next
page until given values are correct.

Example:- 1
<html>
<head>
<title>Form Validation</title>
<script type = "text/javascript">
<!--
// Form validation code will come here.
function validate() {

if( [Link] == "" ) {


alert( "Please provide your name!" );
[Link]() ;
return false;
}
if( [Link] == "" ) {
alert( "Please provide your Email!" );
[Link]() ;
return false;
}
if( [Link] == "" || isNaN( [Link] ) ||
[Link] != 5 ) {

alert( "Please provide a zip in the format #####." );


[Link]() ;
return false;
}
if( [Link] == "-1" ) {
alert( "Please provide your country!" );
return false;
}
return( true );
}
function validateEmail()
{
var emailID = [Link];
atpos = [Link]("@");
dotpos = [Link](".");

if (atpos < 1 || ( dotpos - atpos < 2 ))


{
alert("Please enter correct email ID")
[Link]() ;
return false;
}
return( true );
}
//-->
</script>
</head>

<body>
<form action = "/cgi-bin/[Link]" name = "myForm" > <table cellspacing = "2" cellpadding = "2" border = "1">

<tr>
<td align = "right">Name</td>
<td><input type = "text" name = "Name" /></td>
</tr>

<tr>
<td align = "right">EMail</td>
<td><input type = "text" name = "EMail" /></td>
</tr>
<tr>
<td align = "right">Zip Code</td>
<td><input type = "text" name = "Zip" /></td>
</tr>

<tr>
<td align = "right">Country</td>
<td>
<select name = "Country">
<option value = "-1" selected>[choose yours]</option>
<option value = "1">USA</option>
<option value = "2">UK</option>
<option value = "3">INDIA</option>
</select>
</td>
</tr>

<tr>
<td align = "right"></td>
<td><input type = "submit" value = "Submit" /></td>
</tr>

</table>
</form>
</body>
</html>

Example:- 2
<html>
<body>
<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>
<body>
<form name="myform" method="post"
action="[Link] >validateform()" >
Name: <input type="text" name="name"><br/>
Password: <input type="password" name="password"><br/>
<input type="submit" value="register">
</form>
</body>
</html>

JavaScript Retype Password Validation


<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function matchpass(){
var firstpassword=[Link];
var secondpassword=[Link];

if(firstpassword==secondpassword){
return true;
}
else{
alert("password must be same!");
return false;
}
}
</script>
</head>
<body>

<form name="f1" action="[Link]


matchpass()">
Password:<input type="password" name="password" /><br/>
Re-enter Password:<input type="password" name="password2"/><br/>
<input type="submit">
</form>

</body>
</html>

JavaScript Number Validation


Let's validate the textfield for numeric value only. Here, we are using isNaN() function.

<!DOCTYPE html>
<html>
<head>
<script>
function validate(){
var num=[Link];
if (isNaN(num)){
[Link]("numloc").innerHTML="Enter Numeric value only";
return false;
}else{
return true;
}
}
</script>
</head>

<body>
<form name="myform" action="[Link]
validate()" >
Number: <input type="text" name="num"><span id="numloc"></span><br/>
<input type="submit" value="submit">
</form>

</body>
</html>

JavaScript validation with image


Let’s see an interactive JavaScript form validation example that displays correct and incorrect
image if input is correct or incorrect.

<html>
<body>
<script type="text/javascript">
function validate(){
var name=[Link];
var passwordlength=[Link];
var status=false;
if(name==""){
[Link]("namelocation").innerHTML=
" <img
src='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAH8AAAB/CAMAAADxY+0h
AAAAOVBMVEX///8AAACPj49oaGiBgYF+fn719fWpqalLS0sJCQk5OTmWlpbh4eGSkpJ7e3tu
bm51dXXa2tpTU1PaztA5AAACFElEQVRoge2ba6+DIAyGwbtTdNv//7HzxBi13IX5LjntRy080
hYskAohmrbr5f3Sd20jFnk9APBVHq9l9Dj88gGNaIF4KVvRQfmdQITeLr2A4qVkPvM3eQ/FH
TK8LfxB3CODhV/cxC+Yz3zmM5/5zGc+85n/2/xRlaUaIwjuBrF8tb5WwXhPg0i+2t6Xgfhya2
D5gDj+uCtMQfhpb2B2QRxfHTSqAHx10DcbII5fHjRk7cXXR3WzxxL4cvbg55N2Dr469SifTvz
zrJzD/uO5S6cLaqKbI/6oARxBWBHNLPOPRoDdBcT41vUiev2dSMfmIJyJlnW1iP//UMOaYoD
63u6mC/8/f+chn3id7zVumIuu8z3BFRqi1/maC44WoKN3L9MX8x/q4SrgTU6+5oJtlNQy7iU
6If+jQTg7nn6DbxypzSrf4OuebiJ9n8jXIp1e34SkaEn5P53pZwlKUdP2H9QCsaNP3v9Qj+8S
kp6m87VZsIk/8vPwtRm/infeZ+Nrc/5PfKteTr4hBgJ9n4nf0HnfNbfyweMH+x8c/+D5D17/w
Os/+P8H/v+D8x9w/gfOf8H5P3j/A97/gfe/4P0/+PwDfP4DPv8Cn/+Bzz/R57/o82/0+T/6/gN
9/4O+/0Lf/8HvP+H3v7mF+cxnPvOZz3zmM5/5v8FH17+g638Qwvx/zkfXf6LrX9H1v+j6Z3
T9N7j+/QPMnCdyYLGA3gAAAABJRU5ErkJggg=='/> Please enter your name";
status=false;
}else{
[Link]("namelocation").innerHTML=" <img
src='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAIMAAACNCAMAAACjSTkk
AAAAb1BMVEX///8AAAD8/Pzj4+Pu7u739/cEBATf39+tra309PS7u7uzs7PW1tbBwcHn5+eP
j4+ioqKWlpbPz8/JycmCgoIxMTFHR0cYGBiIiIhiYmJNTU17e3taWlpnZ2dsbGx0dHQoKCg4O
DggICAPDw9AQEApAh4hAAAE00lEQVR4nO1biZKqOBRNQiIhGwmojaJt2/b/f+NkcSGgNa/6
STJTxSnLogXN4e73kgZgwYIFCxYsWLBgwYL/D9D9LS/+AxSyo+1/1iongYodoMUuy+LBEtn
WMYAbkYWDBaEbu/5qBTc4FwO2hwHbIrlfhPXEzq+/8hRSM0DuhXt4w7ZKTSHw4Bt4k8Iug
y1YTRQ7v/zKsThWOWwB6QsM7uAoJF4/QB3uaoDwk+SgwL6vy3sKOVIV6gYMHIX0toBPAz
2kV4S75XILB9jlUIT4unmD88sdyVC4tB+Wwd0YDsmjo43OPNjBlcQ+Q4BG9CaAldPHNkfdp
G+m4CWxKTNQMI8EYd8+0tcLXgrwoYvvJvX6KKZgIVNTAJEtBArpFUHhMEdAk5qCXY4P1b
CCXVoCnoOMhAD79AxCgH5QyBEexQUOk4SNTcmNobjEXpm4o3P3q/YDW7BHNPWcAQFyi
DwCrn3+TEviGAeGI0lLwbURZigEmyUSp2tkbzjOUxA26V2CxbEJ6tS2YEvoODbBU/o8pX5ie
9zMsAYCr13d2eMuNobv1MEJ+dJtNaBgjWEOkKp6rWEe6WE1S3Aq6Hp//tnV7fMs2HzHWeL
81mSJfAjuroMceDk0T+6QnGMKsH0nBU+CRb/f47FxRvZ4jQzvJeGqwyj27Me9gh5dcHx7h9
/AMc7xXK0ZlQxQvVcMCFQ/Ew7wqwDXeYqbO0anrEDYOwmAZ1kgqKNC6PoshnyOLujf7ZQ
IHCYEHB71+qijgh8qfO+dKK202XFCgl5Py/GJN7vlA4hfRhpx9bIVevU1TJb26HOemsH/KB/f
78Gf6+N8Db/mGjN4EmZMwmnDGUNEgs1aOpGxcW4UKDejz46z1i3Ix6rVMD/XYD+iAGcf
+Iy1senHFOqZGVgf+Bj2ULdJ0wA/c9fy0wHPyBwfMWNOVNsxiQiHBDN5NA0SEZoE/a3NTy
8FYbVymnv9Kwn2ioMtKlI9srSF4zSRB8xTzE+ApmXbHft0nR0+vxBDm7DHrp9TOKUcuOCn
FDZJn6GjSZJwSBEhB5iW+jZRpJ63TBK2j5BpQScU1qkpAHUelbGz1ZAv4FLjuJbhaSl44DhW
7jNQAKDLa5AexceAQvqnNAGDODV7DfkcCIiHIHiePYjIW0Qwy0MOAgE4RAY/Cc2zFxOFFO5
brYy7QbHvNPc4645UnzVmm3f8GVwbPtO8489R7k4q9fOyJ0i/32rBggULFixYsGDBggUL3oH
q0c6g28tPyUkVtsqhsBcBPe177p/8VV9GlfslVVT3UaQI+00EjwYQjh1iXdka0moCGJZdU3HQ
GiwMJn8zs2Et01JgoTvaY9YoKnjR84IWJW9pQ0BJC8kVk1wAREBlUKHLXgvNNDAY0BPqsGH
K8OPvByZVJ2ir60IzJjjra2b/wrqsRWcKsZeA1EpyWVMta1BogJiRuu4kqTvNpJagA8ZwwBt78
GtlkLLWSneik7Lk9oZbVjVUF506GdyuNSAd4axdS1p2Tg6kkhyvCyPWWtVIGLAGuEdcAsvh1
3JAui2rRmmGqdKYsqIsrH65MtguVIqmwUZJWpUC+3EpoRRIBBqNGl1RirixeiS6ZtKwFMMC
dHeLdy929zp0mzmg8P+QCFz9Dd38FQVHBfdrHuT+jdc/rKwtGmdQE7UAAAAASUVORK5C
YII='/>";
status=true;
}

if(passwordlength<6){
[Link]("passwordlocation").innerHTML=
" <img
src='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAH8AAAB/CAMAAADxY+0h
AAAAOVBMVEX///8AAACPj49oaGiBgYF+fn719fWpqalLS0sJCQk5OTmWlpbh4eGSkpJ7e3tu
bm51dXXa2tpTU1PaztA5AAACFElEQVRoge2ba6+DIAyGwbtTdNv//7HzxBi13IX5LjntRy080
hYskAohmrbr5f3Sd20jFnk9APBVHq9l9Dj88gGNaIF4KVvRQfmdQITeLr2A4qVkPvM3eQ/FH
TK8LfxB3CODhV/cxC+Yz3zmM5/5zGc+85n/2/xRlaUaIwjuBrF8tb5WwXhPg0i+2t6Xgfhya2
D5gDj+uCtMQfhpb2B2QRxfHTSqAHx10DcbII5fHjRk7cXXR3WzxxL4cvbg55N2Dr469SifTvz
zrJzD/uO5S6cLaqKbI/6oARxBWBHNLPOPRoDdBcT41vUiev2dSMfmIJyJlnW1iP//UMOaYoD
63u6mC/8/f+chn3id7zVumIuu8z3BFRqi1/maC44WoKN3L9MX8x/q4SrgTU6+5oJtlNQy7iU
6If+jQTg7nn6DbxypzSrf4OuebiJ9n8jXIp1e34SkaEn5P53pZwlKUdP2H9QCsaNP3v9Qj+8S
kp6m87VZsIk/8vPwtRm/infeZ+Nrc/5PfKteTr4hBgJ9n4nf0HnfNbfyweMH+x8c/+D5D17/w
Os/+P8H/v+D8x9w/gfOf8H5P3j/A97/gfe/4P0/+PwDfP4DPv8Cn/+Bzz/R57/o82/0+T/6/gN
9/4O+/0Lf/8HvP+H3v7mF+cxnPvOZz3zmM5/5v8FH17+g638Qwvx/zkfXf6LrX9H1v+j6Z3
T9N7j+/QPMnCdyYLGA3gAAAABJRU5ErkJggg=='/> Password must be greater than 6";
status=false;
}else{
[Link]("passwordlocation").innerHTML=" <img
src='[Link]
}

return status;
}
</script>
<form name="f1" action="[Link]
validate()">
<table>
<tr><td>Name:</td><td><input type="text" name="name"/>
<span id="namelocation" style="color:red"></span></td></tr>
<tr><td>Password:</td><td><input type="password" name="password"/>
<span id="passwordlocation" style="color:red"></span></td></tr>
<tr><td colspan="2"><input type="submit" value="register"/> </td></tr>
</table>
</form>
</body>
</html>

JavaScript email validation


We can validate the email by the help of JavaScript.

There are many criteria that need to be follow to validate the email id such as:

o email id must contain the @ and . character


o There must be at least one character before and after the @.

o There must be at least two characters after . (dot).

Let's see the simple example to validate the email field.

<html>
<body>
<script>
function validateemail()
{
var x=[Link];
var atposition=[Link]("@");
var dotposition=[Link](".");
if (atposition<1 || dotposition<atposition+2 || dotposition+2>=[Link]){
alert("Please enter a valid e-mail address \n atpostion:"+atposition+"\n
dotposition:"+dotposition);
return false;
}
}
</script>
<body>
<form name="myform" method="post"
action="[Link] >validateemail();">
Email: <input type="text" name="email"><br/>

<input type="submit" value="register">


</form>
</body>
</html>
Questions:-

1. What is JavaScript? [1]


2. Explain type of JavaScript in detail. [5]
3. Explain JavaScript data types and variables. [5]
4. Write a short note on JavaScript operators. [7]
5. Explain JavaScript control structure with example. [7]
6. Write a short note on mouse events. [5]
7. Explain form events in brief. [5]
8. Write a short note on JavaScript functions. [5]
9. Explain page redirection in JavaScript. [2]
10. Explain JavaScript basic form validations with example. [5]

11. Explain JavaScript data format validations with example. [7]

12. Write a short note on dialog box in JavaScript. [5]

You might also like