Module2 L2

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

Javascript

Module2 continued
OVERVIEW OF JAVASCRIPT
• ORIGINS
• JavaScript, which was developed by Netscape, was originally named
Mocha but soon was renamed LiveScript.
• In late 1995 LiveScript became a joint venture of Netscape and Sun
Microsystems, and its name again was changed, this time to JavaScript.
• A language standard for JavaScript was developed in the late 1990s by the
European Computer Manufacturers Association (ECMA) as ECMA-262.
• The official name of the standard language is ECMAScript.
• JavaScript can be divided into three parts: the core, client side, and server
side.
• The core is the heart of the language, including its operators,
expressions, statements, and subprograms.
• Client-side JavaScript is a collection of objects that support the control of
a browser and interactions with users.
• Server-side JavaScript is a collection of objects that make the language
useful on a Web server.
JAVA
• Java is programming language
• It is strongly typed language
• Types are known at compile time
• Objects in java are static
• Collection of data members and methods is
fixed at compile time
• Object oriented programming language
JAVASCRIPT

• JavaScript is a scripting language


• It is dynamically typed language
• Compile time type
• JavaScript objects are dynamic
• The number of data members and methods
of an object can change during execution
• Object based language
USES OF JAVASCRIPT
• The JavaScript was initially introduced to provide programming capability at both
the server and client ends of web connection
• JavaScript therefore is implemented at 2 ends:
• Client end
• Server end
• The client side JavaScript is embedded in XHTML documents and is interpreted by
the browser
• It also provides some means of computation, which serves as an alternative for
some tasks done at the server side
• Interactions with users through form elements, such as buttons and menus, can
be conveniently described in JavaScript. Because button clicks and mouse
movements are easily detected with JavaScript, they can be used to trigger
computations and provide feedback to the user.
• For example, when a user moves the mouse cursor from a text box, JavaScript can
detect that movement and check the appropriateness of the text box’s value
(which presumably was just filled by the user).
• Even without forms, user interactions are both possible
and simple to program in JavaScript. These interactions,
which take place in dialog windows, include getting input
from the user and allowing the user to make choices
through buttons. It is also easy to generate new content in
the browser display dynamically
• This transfer of task ensures that the server is not
overloaded and performs only required task
• But client side JavaScript cannot replace server side
JavaScript; because server side software supports file
operations, database access, security, networking etc
• JavaScript is also used as an alternative to java applets.
• Programming in JavaScript is much simpler than compared
to java
• JavaScript support DOM [Document Object Model] which
enables JavaScript to access and modify CSS properties and
content of any element of a displayed XHTML document
EVENT-DRIVEN COMPUTATION OF
JAVASCRIPT
• In JavaScript, the actions are often executed in response to actions of the
users of documents like mouse clicks and form submissions.
• This form of computation supports user interactions through the XHTML
form elements on the client display
• One of the common uses of JavaScript is to check the values provided in
forms by users to determine whether the values are sensible.
• The program or script on the server that processes the form data must
check for invalid input data.
• When invalid data is found, the server must transmit that information
back to the browser.
• Since this process is time consuming, we can perform input checks at the
client side itself which saves both server time and internet time.
• However, validity checking is done on the server side because client side
validity checking can be subverted by an unscrupulous user.
BROWSERS AND XHTML/JAVASCRIPT
DOCUMENTS
• If an XHTML document does not include embedded scripts, the browser reads the
lines of the document and renders its window according to the tags, attributes,
and content it finds.
• When a JavaScript script is encountered in the document, the browser uses its
JavaScript interpreter to “execute” the script.
• Output from the script becomes the next markup to be rendered.
• When the end of the script is reached, the browser goes back to reading the
XHTML document and displaying its content.
• There are two different ways to embed JavaScript in an XHTML document:
implicitly and explicitly.
• In explicit embedding, the JavaScript code physically resides in the XHTML
document.
• The JavaScript can be placed in its own file, separate from the XHTML document.
This approach, called implicit embedding, has the advantage of hiding the script
from the browser user.
• When JavaScript scripts are explicitly embedded, they can appear in either part of
an XHTML document—the head or the body—depending on the purpose of the
script.
OBJECT ORIENTATION AND
JAVASCRIPT
• JavaScript is an object-based language
• It supports prototype-based inheritance
• Without class-based inheritance, JavaScript
cannot support polymorphism.
• A polymorphic variable can reference related
methods of objects of different classes within
the same class hierarchy
JAVASCRIPT OBJECTS

• In JavaScript, objects are collections of


properties, which correspond to the members
of classes in Java and C++.
• Each property is either a data property or a
function or method property.
• Data properties appear in two categories:
primitive values and references to other
objects.
• JavaScript uses non-object types for some of its simplest types;
these non-object types are called primitives.
• Primitives are used because they often can be implemented
directly in hardware, resulting in faster operations on their values.
• All objects in a JavaScript program are indirectly accessed through
variables.
• All primitive values in JavaScript are accessed directly—these are
like the scalar types in Java and C++. These are often called value
types.
• The properties of an object are referenced by attaching the name
of the property to the variable that references the object.
• A JavaScript object appears, both internally and externally, as a list
of property–value pairs.
• The properties are names; the values are data values or functions.
• All functions are objects and are referenced through variables.
• The collection of properties of a JavaScript object is dynamic:
Properties can be added or deleted at any time.
GENERAL SYNTACTIC
CHARACTERISTICS
• Scripts can appear directly as the content of a <script> tag.
• The type attribute of <script> must be set to “text/
javascript”.
• The JavaScript script can be indirectly embedded in an
XHTML document with the src attribute of a <script> tag,
whose value is the name of a file that contains the
script—for example,
• <script type = “text/javascript” src = “tst_number.js” > </
script>
• Notice that the script element requires the closing tag,
even though it has no content when the src attribute is
included.
• In JavaScript, identifiers, or names, must
begin with a letter, an underscore ( _ ), or a
dollar sign ($). Subsequent characters may be
letters, underscores, dollar signs, or digits.
There is no length limitation for identifiers.
• JavaScript has 25 reserved words
• In addition, JavaScript has a large collection of
predefined words, including alert, open, java, and self.
• JavaScript has two forms of comments, both of which
are used in other languages. First, whenever two
adjacent slashes (//) appear on a line, the rest of the
line is considered a comment. Second, /* may be used
to introduce a comment, and */ to terminate it, in
both single- and multiple-line comments.
• The XHTML comment used to hide JavaScript uses the
normal beginning syntax, <!--.
• The following XHTML comment form hides the
enclosed script from browsers that do not have
JavaScript interpreters, but makes it visible to
browsers that do support JavaScript:
• The use of semicolons in JavaScript is unusual. The
JavaScript interpreter tries to make semicolons unnecessary,
but it does not always work.
• When the end of a line coincides with what could be the
end of a statement, the interpreter effectively inserts a
semicolon there. But this can lead to problems. For
example,
return
x;
• The interpreter will insert a semicolon after return, making
x an invalid orphan.
• The safest way to organize JavaScript statements is to put
each on its own line whenever possible and terminate each
statement with a semicolon. If a statement does not fit on
a line, be careful to break the statement at a place that will
ensure that the first line does not have the form of a
complete statement.
PRIMITIVES, OPERATIONS, AND EXPRESSIONS
PRIMITIVE TYPES
• JavaScript has five primitive types: Number, String,
Boolean, Undefined, and Null.
• Each primitive value has one of these types.
• JavaScript includes predefined objects that are closely
related to the Number, String, and Boolean types,
named Number, String, and Boolean, respectively.
• These objects are called wrapper objects.
• Each contains a property that stores a value of the
corresponding primitive type.
• The purpose of the wrapper objects is to provide
properties and methods that are convenient for use
with values of the primitive types.
• The difference between primitives and objects is
shown in the following example.
NUMERIC AND STRING LITERALS
• All numeric literals are values of type Number. The
Number type values are represented internally in
double-precision floating-point form.
• Integer literals are strings of digits.
• Floating-point literals can have decimal points,
exponents, or both.
• Exponents are specified with an uppercase or lowercase
e and a possibly signed integer literal.
• The following are valid numeric literals:
72 7.2 .72 72. 7E2 7e2 .7e2 7.e2 7.2E-2

• Integer literals can be written in hexadecimal form by


preceding their first digit with either 0x or 0X.
• A string literal is a sequence of zero or more characters
delimited by either single quotes (‘) or double quotes
(“).
• String literals can include characters specified with
escape sequences, such as \n and \t. If you want
an actual single-quote character in a string literal
that is delimited by single quotes, the embedded
single quote must be preceded by a backslash:
• ‘You\’re the most lovely person I\’ve ever met ‘
• A double quote can be embedded in a double-
quoted string literal by preceding it with a
backslash.
• There is no difference between single-quoted and
double-quoted literal strings.
• The null string (a string with no characters) can be
denoted with either ‘ ’or “ “.
OTHER PRIMITIVE TYPES
• The only value of type Null is the reserved word null,
which indicates no value.
• The only value of type Undefined is undefined.
• The only values of type Boolean are true and false.
DECLARING VARIABLES
• A variable can be declared either by assigning it a
value, in which case the interpreter implicitly declares
it to be a variable, or by listing it in a declaration
statement that begins with the reserved word var.
Initial values can be included in a var declaration, as
with some of the variables in the following
declaration:
• A variable that has been declared but not assigned a
value, has the value undefined.
A variable that has been declared but not assigned a
value, has the value undefined.
NUMERIC OPERATORS
• JavaScript has the typical collection of numeric operators: the binary
operators + for addition, - for subtraction, * for multiplication, / for division,
and % for modulus.
• The unary operators are plus (+), negate (-), decrement (--), and increment
(++). The increment and decrement operators can be either prefix or postfix.
• For example, if the variable a has the value 7, the value of the following
expression is 24:
• (++a) * 3
• But the value of the following expression is 21:

• (a++) * 3
• In both cases, a is set to 8.
• All numeric operations are done in double-precision floating point.
• The precedence rules of a language specify which operator is evaluated first
when two operators with different precedence are adjacent in an expression.
• The associativity rules of a language specify which operator is evaluated first
when two operators with the same precedence are adjacent in an expression.
THE Math OBJECT

The Math object provides a collection of properties of Number objects


and methods that operate on Number objects. The Math object has
methods for the trigonometric functions, such as sin (for sine) and cos
(for cosine), as well as for other commonly used mathematical
operations. Among these are floor, to truncate a number; round, to
round a number; and max, to return the largest of two given numbers.
THE NUMBER OBJECT

The Number object includes a collection of


useful properties that have constant values.
Table lists the properties of Number. These
properties are referenced through Number.
• Any arithmetic operation that results in an error (e.g., division by zero)
or that produces a value that cannot be represented as a double-
precision floating-point number, such as a number that is too large (an
overflow), returns the value “not a number,” which is displayed as NaN.
If NaN is compared for equality against any number, the comparison
fails. The Number object has a method, toString, which it inherits from
Object but overrides. The toString method converts the number
through which it is called to a string. Example: var price = 427,
str_price; ... str_price = price.toString();
THE STRING CATENATION OPERATOR
• JavaScript strings are not stored or treated as
arrays of characters; rather, they are unit
scalar values. String catenation is specified
with the operator denoted by a plus sign (+).
For example, if the value of first is “Harshitha”,
the value of the following expression is
“Harshitha S”:
first + “ S”
IMPLICIT TYPE CONVERSIONS
• The JavaScript interpreter performs several
different implicit type conversions. Such
conversions are called coercions. If either
operand of a + operator is a string, the
operator is interpreted as a string catenation
operator. If the other operand is not a string,
it is coerced to a string. Example1: “August ” +
1977 -> “August 1997” Example2: 7 * “3” ->
21 & will not be evaluated as string
EXPLICIT TYPE CONVERSIONS

• Strings that contain numbers can be converted to numbers


with the String constructor, as in the following code:
var str_value = String(value);
This conversion could also be done with the toString method,
which has the advantage that it can be given a parameter to
specify the base of the resulting number.
var num = 6;
var str_value = num.toString(); //the result is “6”
var str_value_binary = num.toString(2); //the result is “110”
A number also can be converted to a string by catenating it
with the empty string. Also,
var number = Number(aString);
The number in the string cannot be followed by any character
except a space. JavaScript has two predefined string functions
that do not have this problem.
• The parseInt function searches its string
parameter for an integer literal. If one is found at
the beginning of the string, it is converted to a
number and returned. If the string does not begin
with a valid integer literal, NaN is returned.
• The parseFloat function is similar to parseInt, but
it searches for a floating-point literal, which could
have a decimal point, an exponent, or both. In
both parseInt and parseFloat, the numeric literal
could be followed by any nondigit character
without causing any problem

You might also like