WD Unit 3

Download as pdf or txt
Download as pdf or txt
You are on page 1of 31

305-1 WEB DESIGNING

UNIT 3 OVERVIEW OF JAVA SCRIPT


UNIT-3 OVERVIEW OF JAVASCRIPT
Introduction to Javascript
JavaScript is a dynamic computer programming language. It is lightweight and most commonly used
as a part of web pages, whose implementations allow client-side script to interact with the user and
make dynamic pages. It is an interpreted programming language with object-oriented capabilities.
JavaScript was first known as LiveScript, but Netscape changed its name to JavaScript, possibly
because of the excitement being generated by Java. JavaScript made its first appearance in
Netscape 2.0 in 1995 with the name LiveScript. The general-purpose core of the language has
been embedded in Netscape, Internet Explorer, and other web browsers.

• JavaScript is a lightweight, interpreted programming language.


• Designed for creating network-centric applications.
• Complementary to and integrated with HTML.
• Open and cross-platform

3.1 Overview of Client & Server side Scripting Language

1. Client side scripting :


web browsers execute client side scripting. It is use when browsers has all code. Source
code used to transfer from web server to user’s computer over internet and run directly on
browsers. It is also used for validations and functionality for user events.
It allows for more interactivity. It usually performs several actions without going to user. It
cannot be basically used to connect to databases on web server. These scripts cannot
access file system that resides at web browser. It can also used to create “cookies” that
store data on user’s computer.

2. Server side scripting :


Web servers are used to execute server side scripting. They are basically used to create
dynamic pages. It can also access the file system residing at web server. Server-side
environment that runs on a scripting language is a web-server.
Scripts can be written in any of a number of server-side scripting language available. It is
used to retrieve and generate content for dynamic pages. It is used to require to download
plugins. In this load times are generally faster than client-side scripting. When you need to
store and retrieve information a database will be used to contain data. It can use huge
resources of server. It reduces client-side computation overhead. Server sends pages to
request of user/client.

By : Ms. Esha Patel Page 1


305-1 WEB DESIGNING
UNIT 3 OVERVIEW OF JAVA SCRIPT

Difference between client side scripting and server side scripting


Client side scripting Server side scripting

Source code is not visible to user because it’s output


of server side is a HTML page.
Source code is visible to user.

In this any server side technology can be use and it


does not
It usually depends on browser and it’s depend on client.
version.

It runs on user’s computer. It runs on web server.

There are many advantages link with this


like faster. The primary advantage is it’s ability to highly
response times, a more interactive customize, response
application. requirements, access rights based on user.

It does not provide security for data. It provides more security for data.

It is a technique that uses scripts on web server to


It is a technique use in web development produce a response that is customized for each clients
in which scripts runs on clients browser. request.

HTML, CSS and javascript are used. PHP, Python, Java, Ruby are used.

By : Ms. Esha Patel Page 2


305-1 WEB DESIGNING
UNIT 3 OVERVIEW OF JAVA SCRIPT
3.2 Structure of Javascript
JavaScript can be implemented using JavaScript statements that are placed within the <script>...
</script> HTML tags in a web page.
You can place the <script> tags, containing your JavaScript, anywhere within your web page, but it
is normally recommended that you should keep it within the <head> tags.
The <script> tag alerts the browser program to start interpreting all the text between these tags as a
script. A simple syntax of your JavaScript will appear as follows.
<script ...>
JavaScript code
</script>
The script tag takes two important attributes −
• Language − This attribute specifies what scripting language you are using. Typically, its value
will be javascript. Although recent versions of HTML (and XHTML, its successor) have phased
out the use of this attribute.
• Type − This attribute is what is now recommended to indicate the scripting language in use
and its value should be set to "text/javascript".
So your JavaScript segment will look like −
<script language = "javascript" type = "text/javascript">
JavaScript code
</script>

Your First JavaScript Code


Let us take a sample example to print out "Hello World". We added an optional HTML comment that
surrounds our JavaScript code. This is to save our code from a browser that does not support
JavaScript. The comment ends with a "//-->". Here "//" signifies a comment in JavaScript, so we add
that to prevent a browser from reading the end of the HTML comment as a piece of JavaScript code.
Next, we call a function document.write which writes a string into our HTML document.
This function can be used to write text, HTML, or both. Take a look at the following code.
Live Demo
<html>
<body>
<script language = "javascript" type = "text/javascript">
<!--
document.write("Hello World!")
//-->
</script>
</body>
</html>

This code will produce the following result −

By : Ms. Esha Patel Page 3


305-1 WEB DESIGNING
UNIT 3 OVERVIEW OF JAVA SCRIPT
Hello World!

.Semicolons are Optional


Simple statements in JavaScript are generally followed by a semicolon character, just as they are in
C, C++, and Java. JavaScript, however, allows you to omit this semicolon if each of your statements
are placed on a separate line. For example, the following code could be written without semicolons.
<script language = "javascript" type = "text/javascript">
<!--
var1 = 10;
var2 = 20
//-->
</script>

Comments in JavaScript
JavaScript supports both C-style and C++-style comments, Thus −
• Any text between a // and the end of a line is treated as a comment and is ignored by
JavaScript.
• Any text between the characters /* and */ is treated as a comment. This may span multiple
lines.
• JavaScript also recognizes the HTML comment opening sequence <!--. JavaScript treats this
as a single-line comment, just as it does the // comment.
• The HTML comment closing sequence --> is not recognized by JavaScript so it should be
written as //-->.

Example

The following example shows how to use comments in JavaScript.


<script language = "javascript" type = "text/javascript">
<!--
// This is a comment. It is similar to comments in C++

/*
* This is a multi-line comment in JavaScript
* It is very similar to comments in C Programming
*/
//-->
</script>

By : Ms. Esha Patel Page 4


305-1 WEB DESIGNING
UNIT 3 OVERVIEW OF JAVA SCRIPT

3.3 Datatypes and Varaibles

JavaScript Datatypes
One of the most fundamental characteristics of a programming language is the set of data types it
supports. These are the type of values that can be represented and manipulated in a programming
language.
JavaScript allows you to work with three primitive data types −
• Numbers, eg. 123, 120.50 etc.
• Strings of text e.g. "This text string" etc.
• Boolean e.g. true or false.
JavaScript also defines two trivial data types, null and undefined, each of which defines only a
single value. In addition to these primitive data types, JavaScript supports a composite data type
known as object.

JavaScript Variables
Like many other programming languages, JavaScript has variables. Variables can be thought of as
named containers. 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.
You can also declare multiple variables with the same var keyword as follows −
<script type = "text/javascript">
<!--
var money;
var name,age;
//-->
</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.
For instance, you might create a variable named money and assign the value 2000.50 to it later. For
another variable, you can assign a value at the time of initialization as follows.
<script type = "text/javascript">
<!--
var name = "Ali";

By : Ms. Esha Patel Page 5


305-1 WEB DESIGNING
UNIT 3 OVERVIEW OF JAVA SCRIPT
var money;
money = 2000.50;
//-->
</script>

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.

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.
Live Demo
<html>
<body onload = checkscope();>
<script type = "text/javascript">
<!--
var myVar = "global"; // Declare a global variable
function checkscope( ) {
var myVar = "local"; // Declare a local variable
document.write(myVar);
}
//-->
</script>
</body>
</html>

This produces the following result −


Local
JavaScript Variable Names
While naming your variables in JavaScript, keep the following rules in mind.

By : Ms. Esha Patel Page 6


305-1 WEB DESIGNING
UNIT 3 OVERVIEW OF JAVA SCRIPT
• You should not use any of the JavaScript reserved keywords as a variable name. These
keywords are mentioned in the next section. For example, break or boolean variable names
are not valid.
• JavaScript variable names should not start with a numeral (0-9). They must begin with a letter
or an underscore character. For example, 123test is an invalid variable name but _123test is
a valid one.
• JavaScript variable names are case-sensitive. For example, Name and name are two different
variables.

• JavaScript Reserved Words


A list of all the reserved words in JavaScript are given in the following table. They cannot be used as
JavaScript variables, functions, methods, loop labels, or any object names.

abstract else instanceof switch

boolean enum int synchronized

break export interface this

byte extends long throw

case false native throws

catch final new transient

char finally null true

class float package try

const for private typeof

continue function protected var

debugger goto public void

By : Ms. Esha Patel Page 7


305-1 WEB DESIGNING
UNIT 3 OVERVIEW OF JAVA SCRIPT
default if return volatile

delete implements short while

Do import static with

double in super

3.4 Operators

JavaScript includes operators as in other languages.An operator is capable of manipulating a certain


value or operand. Operators are used to perform specific mathematical and logical computations on
operands. In other words, we can say that an operator operates the operands. In JavaScript operators
are used for compare values, perform arithmetic operations etc.

Syntax:

<Left operand> operator <right operand>

<Left operand> operator

JavaScript includes following categories of operators.

1. Arithmetic Operators
2. Comparison Operators
3. Logical Operators
4. Assignment Operators
5. Conditional Operators

Arithmetic Operators

Arithmetic operators are used to perform mathematical operations between numeric operands.

Operator Description

+ Adds two numeric operands.

- Subtract right operand from left operand

By : Ms. Esha Patel Page 8


305-1 WEB DESIGNING
UNIT 3 OVERVIEW OF JAVA SCRIPT
Operator Description

* Multiply two numeric operands.

/ Divide left operand by right operand.

% Modulus operator. Returns remainder of two operands.

++ Increment operator. Increase operand value by one.

-- Decrement operator. Decrease value by one.

The following example demonstrates how arithmetic operators perform different tasks on operands.

Example: Arithmetic Operator

var x = 5, y = 10, z = 15;

x + y; //returns 15

y - x; //returns 5

x * y; //returns 50

y / x; //returns 2

x % 2; //returns 1

x++; //returns 6

x--; //returns 4

+ operator performs concatenation operation when one of the operands is of string type.

The following example shows how + operator performs operation on operands of different data types.

Example: + operator

var a = 5, b = "Hello ", c = "World!", d = 10;

a + b; // "5Hello "

b + c; // "Hello World!"

By : Ms. Esha Patel Page 9


305-1 WEB DESIGNING
UNIT 3 OVERVIEW OF JAVA SCRIPT
a + d; // 15

Comparison Operators

JavaScript language includes operators that compare two operands and return Boolean value true or false.

Operators Description

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

=== Compares equality of two operands with type.

!= Compares inequality of two operands.

> Checks whether left side value is greater than right side value. If yes then returns true otherwise
false.

< Checks whether left operand is less than right operand. If yes then returns true otherwise false.

>= Checks whether left operand is greater than or equal to right operand. If yes then returns true
otherwise false.

<= Checks whether left operand is less than or equal to right operand. If yes then returns true
otherwise false.

The following example demonstrates how comparison operators perform different tasks.

Example: Comparison Operators

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


var x = a;

a == c; // returns true

a === c; // returns false

a == x; // returns true

By : Ms. Esha Patel Page 10


305-1 WEB DESIGNING
UNIT 3 OVERVIEW OF JAVA SCRIPT

a != b; // returns true

a > b; // returns false

a < b; // returns true

a >= b; // returns false

a <= b; // returns true

a >= c; // returns true


a <= c; // returns true

Logical Operators

Logical operators are used to combine two or more conditions. JavaScript includes following logical
operators.

Operator Description

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

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

! ! is known as NOT operator. It reverses the boolean result of the operand (or condition)

Example: Logical Operators

var a = 5, b = 10;

(a != b) && (a < b); // returns true

(a > b) || (a == b); // returns false

(a < b) || (a == b); // returns true

!(a < b); // returns false

!(a > b); // returns true

By : Ms. Esha Patel Page 11


305-1 WEB DESIGNING
UNIT 3 OVERVIEW OF JAVA SCRIPT

Assignment Operators

JavaScript includes assignment operators to assign values to variables with less key strokes.

Assignment
operators Description

= Assigns right operand value to left operand.

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

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

*= Multiply left and right operand values and assign 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.

Example: Assignment operators

var x = 5, y = 10, z = 15;

x = y; //x would be 10

x += 1; //x would be 6

x -= 1; //x would be 4

x *= 5; //x would be 25

By : Ms. Esha Patel Page 12


305-1 WEB DESIGNING
UNIT 3 OVERVIEW OF JAVA SCRIPT
x /= 5; //x would be 1

x %= 2; //x would be 1

Ternary Operator

JavaScript includes special operator called ternary operator :? that assigns a value to a variable based on
some condition. This is like short form of if-else condition.

Syntax:

<condition> ? <value1> : <value2>;

Ternary operator starts with conditional expression followed by ? operator. Second part ( after ? and before :
operator) will be executed if condition turns out to be true. If condition becomes false then third part (after :)
will be executed.

Example: Ternary operator

var a = 10, b = 5;

var c = a > b? a : b; // value of c would be 10


var d = a > b? b : a; // value of d would be 5

Points to Remember

1. JavaScript includes operators that perform some operation on single or multiple operands (data value) and
produce a result.
2. JavaScript includes various categories of operators: Arithmetic operators, Comparison operators, Logical
operators, Assignment operators, Conditional operators.
3. Ternary operator ?: is a conditional operator.

By : Ms. Esha Patel Page 13


305-1 WEB DESIGNING
UNIT 3 OVERVIEW OF JAVA SCRIPT

3.5 Control Structure

JavaScript has number of statements that control flow of the program. There are:

▪ conditionals (if-else, switch) that perform different actions depending on the value of an expression,
▪ loops (while, do-while, for, for-in, for-of), that execute other statements repetitively,
▪ jumps (break, continue, labeled statement) that cause a jump to another part of the program.

onditionals are control structures that perform different actions depending on the value of an
expression.

if-else

The if statement allows to make decision and to execute statement conditionally. If the condition
evaluates to true, statement is executed, otherwise it is not.

if (condition)

statement;

To conditionally execute more than one statement you should use curly braces like below:

if (condition) {

By : Ms. Esha Patel Page 14


305-1 WEB DESIGNING
UNIT 3 OVERVIEW OF JAVA SCRIPT
statement1;

statement2;

It is considered good practice to always enclose code within braces even if only one statement is
to execute.Using an else clause allows to execute another statement if the condition is false:

if (condition) {

statement1;

} else {

statement2;

You can also combine a few if-else statements:

if (condition1) {

statement1;

} else if (condition2) {

statement2;

} else {

statement3;

An example:

By : Ms. Esha Patel Page 15


305-1 WEB DESIGNING
UNIT 3 OVERVIEW OF JAVA SCRIPT
if (weight <= 60) { category = "light"; } else if (weight > 60 && weight <= 90)

category = "middle";

Else

category = "heavy";

switch

The switch statement is similar to the if-else statement. If all of the branches depend on the
value of the same expression, the switch control structure can be used instead of the if-else.

switch (expression) {

case value1:

statement1;

[break;]

case value2:

statement2;

[break;]

default:

statement3;}

When the switch statement is executed, the program attempts to match the value of expression
to a case valel. If the value of expression is equal to a case value, the program executes the
associated statements. If matching is not found, the program looks for the optional default
clause. If it is found, associated statements are executed, if not the program skips all statements
within the switch statement.

By : Ms. Esha Patel Page 16


305-1 WEB DESIGNING
UNIT 3 OVERVIEW OF JAVA SCRIPT
The optional break keyword associated with each case ensures that the program breaks out of
the switch statement once the matched statement is executed. If the break is omitted all
subsequent statements will also be executed.

An example:

switch (option) {

case 1:

type = "small";

break;

case 2:

type = "medium";

break;

case 3:

type = "large";

break;

default:

type = "other";

By : Ms. Esha Patel Page 17


305-1 WEB DESIGNING
UNIT 3 OVERVIEW OF JAVA SCRIPT

Loops in JavaScript

Looping in programming languages is a feature which facilitates the execution of a set of


instructions/functions repeatedly while some condition evaluates to true. For example, suppose we
want to print “Hello World” 10 times. This can be done in two ways as shown below:

Iterative Method
Iterative method to do this is to write the document.write() statement 10 times.

<script type = "text/javascript">

document.write("Hello World\n");

document.write("Hello World\n");

document.write("Hello World\n");

document.write("Hello World\n");

document.write("Hello World\n");

document.write("Hello World\n");

document.write("Hello World\n");

document.write("Hello World\n");

document.write("Hello World\n");

document.write("Hello World\n");

< /script>

By : Ms. Esha Patel Page 18


305-1 WEB DESIGNING
UNIT 3 OVERVIEW OF JAVA SCRIPT

Using Loops
In Loop, the statement needs to be written only once and the loop will be executed 10 times as shown
below:

<script type = "text/javascript">

var I;

for (i = 0; i < 10; i++)

document.write("Hello World!\n");

< /script>

Many things may seem confusing to you in the above program at this point of time but do not worry
you will be able to understand everything about loops in JavaScript by the end of this tutorial. You can
observe that in the above program using loops we have used the document.write statement only once
but still, the output of the program will be same as that of the iterative program where we have used the
document.write statement 10 times.

There are mainly two types of loops:


1. Entry Controlled loops: In this type of loops the test condition is tested before entering the loop
body. For Loop and While Loop are entry controlled loops.
2. Exit Controlled Loops: In this type of loops the test condition is tested or evaluated at the end of
loop body. Therefore, the loop body will execute atleast once, irrespective of whether the test
condition is true or false. do – while loop is exit controlled loop.
JavaScript mainly provides three ways for executing the loops. While all the ways provide similar basic
functionality, they differ in their syntax and condition checking time. Let us learn about each one of
these in details.

By : Ms. Esha Patel Page 19


305-1 WEB DESIGNING
UNIT 3 OVERVIEW OF JAVA SCRIPT
1. while loop: A while loop is a control flow statement that allows code to be executed repeatedly
based on a given Boolean condition. The while loop can be thought of as a repeating if statement.
Syntax :
while (boolean condition)
{
loop statements...
}
Flowchart:

• While loop starts with the checking of condition. If it evaluated to true, then the loop body
statements are executed otherwise first statement following the loop is executed. For this reason
it is also called Entry control loop
• Once the condition is evaluated to true, the statements in the loop body are executed. Normally
the statements contain an update value for the variable being processed for the next iteration.
• When the condition becomes false, the loop terminates which marks the end of its life cycle.

<script type = "text/javaScript">

// JavaScript program to illustrate while loop

var x = 1;

// Exit when x becomes greater than 4

while (x <= 4)

By : Ms. Esha Patel Page 20


305-1 WEB DESIGNING
UNIT 3 OVERVIEW OF JAVA SCRIPT
{

document.write("Value of x:" + x + "<br />");

// increment the value of x for

// next iteration

x++;}

< /script>

Output:
Value of x:1
Value of x:2
Value of x:3
Value of x:4
2. for loop: for loop provides a concise way of writing the loop structure. Unlike a while loop, a for
statement consumes the initialization, condition and increment/decrement in one line thereby
providing a shorter, easy to debug structure of looping.
Syntax:

for (initialization condition; testing condition;


increment/decrement)
{
statement(s)
}

By : Ms. Esha Patel Page 21


305-1 WEB DESIGNING
UNIT 3 OVERVIEW OF JAVA SCRIPT
Flowchart:

Initialization condition: Here, we initialize the variable in use. It marks the start of a for loop. An
already declared variable can be used or a variable can be declared, local to loop only.
Testing Condition: It is used for testing the exit condition for a loop. It must return a boolean
value. It is also an Entry Control Loop as the condition is checked prior to the execution of the
loop statements.
Statement execution: Once the condition is evaluated to true, the statements in the loop body are
Executed.

Increment/ Decrement: It is used for updating the variable for next iteration.
Loop termination:When the condition becomes false, the loop terminates marking the end of its
life cycle.

<script type = "text/javaScript">

// JavaScript program to illustrate for loop

var x;

// for loop begins when x=2

// and runs till x <=4

for (x = 2; x <= 4; x++)

By : Ms. Esha Patel Page 22


305-1 WEB DESIGNING
UNIT 3 OVERVIEW OF JAVA SCRIPT
{

document.write("Value of x:" + x + "<br />");

< /script>

Output:
Value of x:2
Value of x:3
Value of x:4

for…in loop

JavaScript also includes another version of for loop also known as the for..in Loops. The for..in
loop provides a simpler way to iterate through the properties of an object. This will be more clear
after leaning objects in JavaScript. But this loop is seen to be very useful while working with
objects.
Syntax:
for (variableName in Object)
{
statement(s)
}
In each iteration, one of the properties of Object is assigned to the variable
named variableName and this loop continues until all of the properties of the Object are processed.
Lets take an example to demonstrate how for..in loop can be used to simplify the work.

<script type = "text/javaScript">

// JavaScript program to illustrate for..in loop

// creating an Object

var languages = { first : "C", second : "Java",

By : Ms. Esha Patel Page 23


305-1 WEB DESIGNING
UNIT 3 OVERVIEW OF JAVA SCRIPT
third : "Python", fourth : "PHP",

fifth : "JavaScript" };

// iterate through every property of the

// object languages and print all of them

// using for..in loops

for (itr in languages)

{ document.write(languages[itr] + "<br >");

}< /script>

Output:
C
Java
Python
PHP
JavaScript
do while: do while loop is similar to while loop with only difference that it checks for condition after
executing the statements, and therefore is an example of Exit Control Loop.
Syntax:
do
{
statements..
}
while (condition);

By : Ms. Esha Patel Page 24


305-1 WEB DESIGNING
UNIT 3 OVERVIEW OF JAVA SCRIPT
Flowchart:

do while loop starts with the execution of the statement(s). There is no checking of any condition for
the first time.

After the execution of the statements, and update of the variable value, the condition is checked for true
or false value. If it is evaluated to true, next iteration of loop starts.

When the condition becomes false, the loop terminates which marks the end of its life cycle.

It is important to note that the do-while loop will execute its statements atleast once before any
condition is checked, and therefore is an example of exit control loop.

<script type = "text/javaScript">

// JavaScript program to illustrate do-while loop

var x = 21;

do

// The line while be printer even

By : Ms. Esha Patel Page 25


305-1 WEB DESIGNING
UNIT 3 OVERVIEW OF JAVA SCRIPT
// if the condition is false

document.write("Value of x:" + x + "<br />");

x++;

} while (x < 20);

< /script>

Output:
Value of x: 21
Infinite loop
One of the most common mistakes while implementing any sort of looping is that that it may not ever
exit, that is the loop runs for infinite time. This happens when the condition fails for some reason.
Examples:

<script type = "text/javaScript">

// JavaScript program to illustrate infinite loop

// infinite loop because condition is not apt

// condition should have been i>0.

for (var i = 5; i != 0; i -= 2)

document.write(i);

By : Ms. Esha Patel Page 26


305-1 WEB DESIGNING
UNIT 3 OVERVIEW OF JAVA SCRIPT
}

var x = 5;

// infinite loop because update statement

// is not provided.

while (x == 5)

document.write("In the loop");}

< /script>

Break and Continue Statement


Break statement: The break statement is used to jump out of a loop. It can be used to “jump out” of a
switch() statement. It breaks the loop and continues executing the code after the loop .

e.g

<script>

var i;

for (i = 1; i < 10; i++)

if (i === 6)

break;

Document.write("Hello" + i + "<br>");

By : Ms. Esha Patel Page 27


305-1 WEB DESIGNING
UNIT 3 OVERVIEW OF JAVA SCRIPT
</script>

Output:

Hello1

Hello2

Hello3

Hello4

Hello5

Continue statement: The continue statement “jumps over” one iteration in the loop. It
breaks iteration in the loop and continues executing the next iteration in the loop.

<script>

var i;

for (i = 1; i < 8; i++)

if (i === 6)

continue;

Document.write("Hello" + i + "<br>");

</script>

Output:

Hello1

By : Ms. Esha Patel Page 28


305-1 WEB DESIGNING
UNIT 3 OVERVIEW OF JAVA SCRIPT
Hello2

Hello3

Hello4

Hello5

Hello7

3.6 Javascript String and Events

Javascript String and Methods

The JavaScript string is an object that represents a sequence of characters.

There are 2 ways to create string in JavaScript

1. By string literal
2. By string object (using new keyword)

1) By string literal

The string literal is created using double quotes. The syntax of creating string using string literal is given below:

var stringname="string value";

Let's see the simple example of creating string literal.161

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

Output:

This is string literal

2) By string object (using new keyword)

The syntax of creating string object using new keyword is given below:

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

Here, new keyword is used to create instance of string.

By : Ms. Esha Patel Page 29


305-1 WEB DESIGNING
UNIT 3 OVERVIEW OF JAVA SCRIPT
Let's see the example of creating string in JavaScript by new keyword.

<script>
var stringname=new String("hello javascript string");
document.write(stringname);
</script>

Output:

hello javascript string

JavaScript String Methods


Let's see the list of JavaScript string methods with examples.

Methods Description

charAt() It provides the char value present at the specified index.

concat() It provides a combination of two or more strings.

indexOf() It provides the position of a char value present in the given string.

lastIndexOf() It provides the position of a char value present in the given string by searching a character
from the last position.

replace() It replaces a given string with the specified replacement.

substring() It is used to fetch the part of the given string on the basis of the specified index.

slice() It is used to fetch the part of the given string. It allows us to assign positive as well
negative index.

split() It splits a string into substring array, then returns that newly created array.

trim() It trims the white space from the left and right side of the string.

By : Ms. Esha Patel Page 30


305-1 WEB DESIGNING
UNIT 3 OVERVIEW OF JAVA SCRIPT

JavaScript Events
The change in the state of an object is known as an Event. In html, there are various events which represents that some activity is
performed by the user or by the browser. When javascript code is included in HTML, js react over these events and allow the execution.
This process of reacting over the events is called Event Handling. Thus, js handles the HTML events via Event Handlers.

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

Some of the HTML events and their event handlers are:

Mouse events:

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

mouseup onmouseup When the mouse button is released over the element

Keyboard events:

Event Performed Event Handler Description

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

Form events:

Event Performed Event Handler Description

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

By : Ms. Esha Patel Page 31

You might also like