Sei sulla pagina 1di 15

Web Technology Sumit Gupta

Web Technology Notes


Unit 3

Introduction to Java Script

Question 1: Short Note on Java Script


Or What is JavaScript, Benefits and usage of JavaScript.

Answer 1: JavaScript was originally developed by Brendan Eich of Netscape under the name
Mocha, which was later renamed to LiveScript, and finally to JavaScript. The change of name
from LiveScript to JavaScript roughly coincided with Netscape adding support for Java
technology in its Netscape Navigator web browser.

Java Script consists of three parts.

1. Core: It includes operators, expressions, statements and subprograms


2. Client Side: It is a collection of objects using which one can have control over the
browser and user browser interaction is possible
3. Server Side: It is a collection of objects using which one can access the database on
the server

Netscape first introduced a JavaScript interpreter in Navigator 2. Interpreter was an extra


software component in the browser that was capable of interpreting JavaScript source code
inside an HTML document. This meant that Web page authors using no more than a simple
text editor could place special instructions or programs directly inside Web pages to make
them more dynamic and interactive. For example, JavaScript can be used to:

• Validate user input in an HTML form before sending the data to a server;
• Build forms that respond to user input without accessing a server;
• Change the appearance of HTML documents and dynamically write HTML into
separate Windows;
• Open and close new Netscape windows or frames;
• Manipulate HTML "layers" including hiding, moving, and allowing the user to drag
them around a browser window;
• Build small but complete client side programs.

Advantage

JavaScript gives web authors an unprecedented degree of control over the behaviour of
Netscape and the behaviour of their documents. You can do things with 20 lines of JavaScript
that will significantly reduce the load on your server, give the user better feed back, and
enhance the appearance of your web pages. JavaScript is often the most efficient solution to
many Web authoring problems. JavaScript is also an easy language to get started using. With
little more than a text editor a few helpful websites and some interest it is possible to produce
some but useful scripts.
Its an event driven programming. Script executes on the click of mouse or hit on keyboard.

1
Web Technology Sumit Gupta

Learning JavaScript

Netscape and others have claimed that JavaScript can be learned by anyone who can write
HTML. While this is probably true, learning to program in JavaScript is not as simple as
creating HTML documents. Even programmers who are new to event-driven programming
find learning JavaScript often requires a significant investment of time. On the other hand,
anyone who can write HTML can, with a certain amount of effort, learn to incorporate and
modify prewritten JavaScript functions into their pages.

Learning to program in JavaScript requires learning two things at once. One is learning the
JavaScript language itself, including things like how to declare functions, looping and
conditional branching constructs, and the other aspects of the language. The second part of
learning JavaScript is learning to write scripts that interact with HTML objects and the Web
browser. For example, if you want to write a function that checks some user input in an
HTML form, you usually need to do two things: first, you must write a segment of code to
correctly check data (a function) and second, have your function called by Netscape when a
user enters something into a field in the form. Writing a function is part of the language.
Writing code to have it called by Netscape is part of working with the HTML page and the
browser. When you learn to program in JavaScript you are usually learning to do both things
at the same time.

Answer 1 ended

Question 2: Difference between Java and JavaScript

Answer 2:

Java JavaScript
1) It’s a programming language 1) It’s a scripting language
2) Its an Object oriented language 2) Its not an object oriented. Its object model
which is far more different than a typical
object oriented language such as java, c++
3) Java is strongly typed language and the 3) In JavaScript variables need not to be
type checking is done at compile time declared before use. Checking the
compatibility of type can be done
dynamically
4) Objects in java are static, that means the 4) Objects are dynamic.
number of data members and methods are
fixed at compile time

Answer 2 Ended

2
Web Technology Sumit Gupta

Question 3: Describe Basic concept of JavaScript

Answer 3: In Web Programming two type of script are popularly user

• text/css
• text/javascript

We can embed the JavaScript directly or indirectly in HTML/XHTML

In case of direct we write the script in following manner

<HTML>

<script type=”text/javascript”>

….

….

….

</script>

</HTML>

Where else in indirect we write script in different file and then call it in html program

<HTML>

<script type=”text/javascript” scr = “MyPage.js”>

….

….

….

</script>

</HTML>

Advantage of writing script in indirect method is that script is hidden to browser user.

Identifiers user in JavaScript

Identifiers are the names given to the variables. These variables hold the data value. Some
conventions are being followed in JavaScript for identifiers

1. It must begin with either letter or underscore or $ sign


2. There is no limit on the length of variable
3. Letters in identifier are case sensitive.

3
Web Technology Sumit Gupta

Reserve Word in JavaScript

break continue delete for in return throw var with


case default else function switch try void catch do
finally if new this typeof while

Writing Comments in JavaScript

1. // is used
2. /* ……………. */ is used
3. <!--> and <--> is used

Semicolon

While writing the JavaScript the programmer must give semicolon at the end of the statement

Answer 3 Ended

Question 4 : What JavaScript can do

Answer 4:

1. Validate User Input


o Checking a Social Insurance Number: - -
o Checking a Password:
o Checking numeric values:
o Checking a file type before uploading it:
2. Forms that respond to user input without accessing a server
o Forms that load a URL

o Forms that Calculate

3. Write information into HTML documents using Javascript Statements


o Programed ouput via document.write();
o Adjust document colours
o Change/rewrite images in a document
4. Open and Close Netscape Windows and Frames

4
Web Technology Sumit Gupta

Create new Netscape Windows with documents or programmed output


o
Create Framesets and Frames with programmed output or containing HTML
o
5. build small but complete client side programs
o Calculators
o Games

o Multiwindow applications

Answer 4 ended

Question 5: How Variables are declared in JavaScript and what type of data types are used in
JavaScript. Also describe the operators used in JavaScript

Answer 5: Description of Data types are as follows

Numbers
• "no explicit distinction between integers and real" numbers though integers may be
stored differently than floating point or real numbers.
• Here are some literal numbers being assigned to a variable (not a complete sampling):
• x = 8 //integer
• x = .7343 //floating point
• x = -4.3e3 //same as -4.3 × 103
• x = 4.3e-3 //same as 4.3 × 10-3

Boolean Values
• trueor false are the two Boolean values
• Examples when true or false values result from an expression (not a complete
sampling):
• 10 < 11 //will be evaluated to result in the value true
• 10 > 11 //will be evaluated to false

Strings

5
Web Technology Sumit Gupta

• Strings can be created by assigning a literal value to a variable or by creating a String


object initialized with a literal string.
• msg = "I there is no end to the details I have to remember?"
• msg = new String("Is there is not end to the details I have to
remember?")

null
• null - "special key word denoting a null value"

x = null

Variable Declaration is done in following manner

In JavaScript we can declare the variable using reserve keyword var. The value of this
variable can be any thing, it can e numeric or string or Boolean

E.g.

var a, b, c;

var string;

a=2 ;

b=3;

c= 4;

string = “this is string”;

Operators

Arithmetic +,-,*,/ and %


Relational <, >, <=, >=, == and !=
Logical &&, ||
Assignment =
Increment ++
Decrement --

Answer 5 Ended

Question 6 : Define implicit and explicit conversion

Answer 6:

Implicit type conversion


6
Web Technology Sumit Gupta

JavaScript support implicit type conversion. Such conversions are called as coercions.
Example: suppose operator A with type number and want to concatenate it with operator B
which is a String type then the number operand gets converted into string type. JavaScript
supports automatic conversion. This is implicit conversion

“Server No” + 10

Output will be “Server No 10”

Explicit Type conversion

Such kinds of operation are done force fully.

Example: Numeric value can to converted to string type using toString method

var my_num = 2;

var my_str ;

my_str = my_num.toString();

This results the value of my_str as “2”

Asnwer 6 ended

Question 7

Describe document.write property in JavaScript

One of JavaScript's strengths is its ability to work with objects. In object-oriented


programming and scripting languages, objects are a way to group or package together
information and methods of working with this information in a convenient way. In order to
access or change the attributes and contents of a Web page JavaScript provides a convenient
object called the document object. According to Netscape it "contains information on the
current document, and provides methods for displaying HTML output to the user." Here is a
simple example broken down into four parts:

7
Web Technology Sumit Gupta

document.write("<P>Hello
World</P>")
document
An application object that contains information about the document loaded into a
frame or window. In the JavaScript documentation the information about an object is
referred to as its properties. Some of the properties of the document object can be
changed others are read only.

The dot between the document object and the write() method is significant. The dot
operator allows you to access information (object properties) and methods for working
with that information in an object. The method or property of an object are on the right
side of the dot and the object is on the left side. For example, information about the
document that contains the script is available using the document object, the dot
notation, and the names of properties of the document object:

document.bgColor - makes it possible to get or set the background colour of the


document
document.location - contains the URL for the current document
document.lastModified - holds the date when the document was last modified on
server

write()
write() is a method (also called a function) belonging to the document object.
write() will output a string of text to the document. The round brackets following the
word write are required. Any JavaScript expression can be placed inside the round
brackets. The expression will be evaluated and the result converted, if necessary, to
text to be written into the current Web page.

"<P>Hello World</P>"
The double quoted text is a "literal" string of text including HTML markup. In this
case the literal text - the actual series of text characters - will be written into the
current Web page.

Answer 7 completed

Question 8:

Describe about Conditional statements and loops in JavaScript

Answer 8:

• if statements;

8
Web Technology Sumit Gupta

• if else statements;
• comparison operators such as: <, <=, >, >=, ==, and != when used with numbers;
• and introduces the else if construct and the
• logical operators && and ||.

Comparison Operators
The following table provides some examples of what boolean value is returned (true or
false) when two numbers are compared. Unless, you are already familiar with C, C++, Perl,
or Java operators take a moment to read through each table and assure yourself that the results
makes sense. Note that if hour contains a string (and not a number) the JavaScript interpreter
will attempt to convert it to a number before making the comparison.

Less than ( < )

Statement result
hour = 2
true
result = hour < 3

hour = 2
false
result = hour < 2

hour = 2
false
result = hour < 1

Less than or equal ( <= )


Statement result
hour = 2
true
result = hour <= 3

hour = 2
true
result = hour <= 2

hour = 2
false
result = hour <= 1

Greater than ( > )

Statement result
hour = 2
false
result = hour > 3

hour = 2
false
result = hour > 2

9
Web Technology Sumit Gupta

hour = 2
true
result = hour > 1

Greater than or equal ( >= )

Statement result
hour = 2
false
result = hour >= 3

hour = 2
true
result = hour >= 2

hour = 2
true
result = hour >= 1

Equal ( == )

Statement result
hour = 2
false
result = hour == 3

hour = 2
true
result = hour == 2

hour = 2
false
result = hour == 1

Not equal ( != )

Statement result
hour = 2
true
result = hour != 3

hour = 2
false
result = hour != 2

hour = 2
true
result = hour != 1

IF END

Switch

switch
10
Web Technology Sumit Gupta

switch (expression) {
case 19:
statement
break
case true:
statement
break
case "hello":
statement
break
default:
statement
break
}

while loop

while(terminating condition)

Some statement;

Stepping condition

do while

do

…….

}while(condition )

for loop

for(x=1; x<=10; x++) // initial cond; terminating cond; stepping cond

…..;

11
Web Technology Sumit Gupta

Answer 8 ended

Question 9

How are function defined in JavaScript

Answer 9

An important part of JavaScript is the ability to create new functions within scripts. These
functions are named segments of JavaScript statements. These statements usually have a
single purpose, such as performing a complex calculation or verifying the data entered into an
HTML form. Functions can be passed copies of variables or references to objects to work
with. Just as with built in functions, this is done in the parameter list. JavaScript functions that
you define can be placed inside script tags anywhere in the document. However, they should
be placed in the head of the document to guarantee they are loaded before being called from
script statements in the body of the document. Here is the format for defining a JavaScript
function:

function functionName(parameter_1, parameter_2, .. parameter_n){


statement1
statement2
statementn
}

The keyword function precedes the name of the function. A function name is like a variable
name in that it must start with a character and must not be the same as a JavaScript key word.
The parameter list is a comma separated list of variable names inside round brackets
immediately following the function name. The statements to be executed when the function is
called are contained inside the function body and are contained within curly braces.

Here is a function that finds the maximum value of two numbers. Note that the function
determines which number is largest and returns the largest value using the return statement.
The value returned will take the place of the function in the calling expression - see the
example below.

function getMax(n1, n2){


if (n1 < n2)
return n2
else
return n1
}

Answer 9 ended

Question 10

How Array is initialize in JavaScript

Answer 10
12
Web Technology Sumit Gupta

There are two methods to create array in JavaScript

1)

anArray = new Array(5);

2)

anArray = new Array(11,12,13,14,15);

Answer 10 ended

Question 11

How objects are declared in JavaScript

Answer 11

Creating an Object
To create your own JavaScript objects you need to:

1. call a function using the key word: new


2. either write a special "constructor" function or call the Object(), Array(), Date() or
other predefined constructor function.

Why write your own function? It is often useful to create an object with a standard set of
properties and methods. Because the function adds one set of properties and methods it in
effect constructs an object of a certain type. If a particular type of object is wanted a
constructor function can be designed to create it as needed. For example suppose we want to
create an online quiz. A nice approach to this problem is to create a series of question objects
that contain properites that include the question and the correct answer. Rather than creating
each object and then adding properties one-by-one, we can pass the property values into the
question function:

function Question(question, answer){


this.question = question
this.answer = answer
}

theQuestion = new Question("What is the sum of 5 and 3?", 8)

In this example the function named Question() expects two parameters: question and
answer. These are assigned to the properties this.question and this.answer.

13
Web Technology Sumit Gupta

The keyword this refers to the object that has just been created by the new operator. The
properties of the object are created and receive values in the two assignment statements in the
Question() function. In this example each paramater value is passed to one of the object's
properties of the same name. The dot notation this.question indicates the the property
"question" whereas the variable "question" from the parameter list and in the body of the
function stands without a dot and is therefore a simple variable.

Here is the line of code that creates a Question object:

theQuestion = new Question("What is the sum of 5 and 3?", 8)

Step-by-step here is what happens when this statement is executed:

1. the new operator creates an object in memory and passes a reference to the new object
to the constructor function: Question();
2. the reference to the new object is available inside the Question() function using the
keyword this which is used to create and assign values to the two properties
question and answer;
3. a reference to the newly created and initialized object is returned and assinged to the
theQuestion variable.

Now that theQuestion variable holds a reference to an object, it can be treated like an object
with properties that can be read and set. For example:

theQuestion.answer = 99
alert("The answer is: " + theQuestion.answer)

The new operator and the Question() function can be used to create as many "Question"
objects as are needed (or that can fit in memory):

aQuestion = new Question("What is the sum of 7 and 3?", 10)


bQuestion = new Question("What is the sum of 5 and 7?", 12)
cQuestion = new Question("What is the sum of 7 and 7?", 14)

Adding Properties
It is always possible to add new properties to an object - even after initializing it with a
function. For example:

function Question(question, answer){


this.question = question
this.answer = answer
}

theQuestion = new Question("What is the sum of 5 and 3?", 8)


theQuestion.hint = "5 + 3 is like 5 + 1 + 2."

Once the object, with or without any properties is created, we can always add new properties.
Just because we add a property to one object however, does not mean it has to be added to all
objects of that "type."

function Question(question, answer){

14
Web Technology Sumit Gupta

this.question = question
this.answer = answer
}

firstQuestion = new Question("What is the sum of 5 and 3?", 8)


firstQuestion.hint = "5 + 3 is like 5 + 1 + 2."
secondQuestion = new Question("What is the sum of 6 and 3?", 9)

Only the firstQuestion object in the example above has a hint property. The
secondQuestion object does not. Since both objects were created with the same function
they both have question and answer properties.

Answer 11 ended

15

Potrebbero piacerti anche