javascript. - originally developed by netscape, as livescript. - became a joint venture of netscape...

68
JavaScript JavaScript

Upload: bruno-preston

Post on 31-Dec-2015

219 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: JavaScript. - Originally developed by Netscape, as LiveScript. - Became a joint venture of Netscape and Sun in 1995, renamed JavaScript - Became a joint

JavaScriptJavaScript

Page 2: JavaScript. - Originally developed by Netscape, as LiveScript. - Became a joint venture of Netscape and Sun in 1995, renamed JavaScript - Became a joint

- - Originally developed by Netscape, as LiveScript.Originally developed by Netscape, as LiveScript.

- Became a joint venture of Netscape and Sun in 1995, - Became a joint venture of Netscape and Sun in 1995, renamed JavaScriptrenamed JavaScript

- Now standardized by the European Computer - Now standardized by the European Computer manufacturers Association as ECMA-262.manufacturers Association as ECMA-262.

- This standard is also approved by ISO as ISO-16262.- This standard is also approved by ISO as ISO-16262.

- The official name of the standard language is - The official name of the standard language is ECMAScript.ECMAScript.

- Current version of JavaScript is v3- Current version of JavaScript is v3

Overview of JavaScript: OriginsOverview of JavaScript: Origins

Page 3: JavaScript. - Originally developed by Netscape, as LiveScript. - Became a joint venture of Netscape and Sun in 1995, renamed JavaScript - Became a joint

• JavaScript is divided into 3 parts:JavaScript is divided into 3 parts:• CoreCore

– It is a heart of the language, including its operators, expressions, It is a heart of the language, including its operators, expressions, statements and subprograms. statements and subprograms.

• Client-sideClient-side– Library of objects supporting browser control and user interactions.Library of objects supporting browser control and user interactions.– It is embedded in XHTML documents and is interpreted by the It is embedded in XHTML documents and is interpreted by the

browser.browser.

• Server-sideServer-side– Library of objects that support use in web servers (connections Library of objects that support use in web servers (connections

with db). with db). – Supports file operations, db access, and networking (Client-side JS Supports file operations, db access, and networking (Client-side JS

supports none of these).supports none of these).– Server-side JavaScript is used less far frequently than Client-side Server-side JavaScript is used less far frequently than Client-side

JavaScript.JavaScript.

JavaScript ComponentsJavaScript Components

Page 4: JavaScript. - Originally developed by Netscape, as LiveScript. - Became a joint venture of Netscape and Sun in 1995, renamed JavaScript - Became a joint

•Java is a object oriented language.Java is a object oriented language.•JavaScript is a scripting language.JavaScript is a scripting language.

•JavaScript and java is only related through syntax of JavaScript and java is only related through syntax of expressions, assignment statements and control statement.expressions, assignment statements and control statement.

•Java was created by Sun micro systems and Js by Java was created by Sun micro systems and Js by Netscape.Netscape.

•Java is strongly typed language. Types are all known at Java is strongly typed language. Types are all known at compile time and operand types are checked for compile time and operand types are checked for compatibility. compatibility. •But variables in JavaScript need not be declared and are But variables in JavaScript need not be declared and are dynamically typed.dynamically typed.

Differences b/n Java and JavaScriptDifferences b/n Java and JavaScript

Page 5: JavaScript. - Originally developed by Netscape, as LiveScript. - Became a joint venture of Netscape and Sun in 1995, renamed JavaScript - Became a joint

• JavaScript is a sequence of statements to be interpreted JavaScript is a sequence of statements to be interpreted (or executed) by the browser. (or executed) by the browser.

• browser uses its Js interpreter to ‘execute’ the script.browser uses its Js interpreter to ‘execute’ the script.

• JavaScript is usually embedded directly into HTML or JavaScript is usually embedded directly into HTML or XHTML pages.XHTML pages.

• Statements can appear either in head or body part, Statements can appear either in head or body part, depending on the purpose.depending on the purpose.

• It is most popular client-side scripting language. It is most popular client-side scripting language.

• Works in all major browsers, such as IE, Firefox, chrome, Works in all major browsers, such as IE, Firefox, chrome, opera safari.opera safari.

• Js is a loosely typed language.Js is a loosely typed language.

What is JavaScript?What is JavaScript?

Page 6: JavaScript. - Originally developed by Netscape, as LiveScript. - Became a joint venture of Netscape and Sun in 1995, renamed JavaScript - Became a joint

• Read Read and and write new elementswrite new elements in text, Manipulate or in text, Manipulate or move text.move text.

• Create Create pop-up windows.pop-up windows.

• Perform Perform mathematical calculationsmathematical calculations on data. on data.

• React to React to eventsevents, such as a mouse moving over an image , such as a mouse moving over an image or clicking a button.or clicking a button.

• Retrieve the Retrieve the current date and timecurrent date and time from a user’s from a user’s computer or the last time a document was modified.computer or the last time a document was modified.

• Determine the Determine the user’s screen size, browser version, or user’s screen size, browser version, or screen resolutionscreen resolution..

• Perform actions based upon conditions such as Perform actions based upon conditions such as alertingalerting users if they enter the wrong information into a form or if users if they enter the wrong information into a form or if they press a certain button.they press a certain button.

• JavaScript can be used to create JavaScript can be used to create cookiescookies..

Applications of JavaScriptApplications of JavaScript

Page 7: JavaScript. - Originally developed by Netscape, as LiveScript. - Became a joint venture of Netscape and Sun in 1995, renamed JavaScript - Became a joint

– A JavaScript statement is a command to the browser, the A JavaScript statement is a command to the browser, the purpose of the command is to tell the browser what to do.purpose of the command is to tell the browser what to do.

– JavaScript statements are Case Sensitive.JavaScript statements are Case Sensitive.

There are three places where you can put your There are three places where you can put your JavaScript:JavaScript:

• In the In the <head> of a page: These scripts will be called when an <head> of a page: These scripts will be called when an event triggers them.event triggers them.

– Normally function definitions and codes associated with form Normally function definitions and codes associated with form elements such as buttons (which react to user interactions) appear elements such as buttons (which react to user interactions) appear in the head section.in the head section.

• In the In the <body> section: These scripts will run as the page loads.<body> section: These scripts will run as the page loads.

• In an external file.In an external file.

JavaScript StatementsJavaScript Statements

Page 8: JavaScript. - Originally developed by Netscape, as LiveScript. - Became a joint venture of Netscape and Sun in 1995, renamed JavaScript - Became a joint

• JavaScript is NOT an JavaScript is NOT an object-orientedobject-oriented programming programming language but language but object basedobject based scripting language. scripting language.

• JavaScript objects are collections of JavaScript objects are collections of propertiesproperties, , which are like the members of classes in Java and C+which are like the members of classes in Java and C++.+.

• Properties can be data properties or method Properties can be data properties or method properties.properties.

• All JavaScript objects are accessed through All JavaScript objects are accessed through references.references.

JavaScript ObjectsJavaScript Objects

Page 9: JavaScript. - Originally developed by Netscape, as LiveScript. - Became a joint venture of Netscape and Sun in 1995, renamed JavaScript - Became a joint

• Ex: airplane (object name)Ex: airplane (object name)– ModelModel (property list)(property list)– PricePrice– speedspeed– FuelFuel

• In JavaScript, the properties of objects are referred to by the In JavaScript, the properties of objects are referred to by the structure:structure:

  object-name object-name . . property-nameproperty-name

• methods might be referred as:methods might be referred as:

airplaneairplane..description()description()airplaneairplane..distance()distance()

Example:Example:

Page 10: JavaScript. - Originally developed by Netscape, as LiveScript. - Became a joint venture of Netscape and Sun in 1995, renamed JavaScript - Became a joint

JavaScript can be embedded either directly or indirectly in XHTML JavaScript can be embedded either directly or indirectly in XHTML documents.documents.

Ex:Ex: <script type=”text/JavaScript” <script type=”text/JavaScript” src=”tst_number.js”>src=”tst_number.js”>

// statements appear if src is omitted.// statements appear if src is omitted.

</script></script>

1. Scripts can appear directly as the content of a 1. Scripts can appear directly as the content of a <script> tag.<script> tag.

2. The type attribute of <script> must be set to 2. The type attribute of <script> must be set to “text/JavaScript”.“text/JavaScript”.

3. The JavaScript can be indirectly embedded in an XHTML 3. The JavaScript can be indirectly embedded in an XHTML document using the src attribute of a <script> tag, whose value document using the src attribute of a <script> tag, whose value is name of a file that contains the script.is name of a file that contains the script.

General Syntactic CharacteristicsGeneral Syntactic Characteristics

Page 11: JavaScript. - Originally developed by Netscape, as LiveScript. - Became a joint venture of Netscape and Sun in 1995, renamed JavaScript - Became a joint

JavaScript has large collection of JavaScript has large collection of predefined words predefined words which are referred as which are referred as keywordskeywords..

JScript Keywords

break false in this void

continue for new True while

delete function null typeof with

else if return var  

JavaScript keywordsJavaScript keywords

Page 12: JavaScript. - Originally developed by Netscape, as LiveScript. - Became a joint venture of Netscape and Sun in 1995, renamed JavaScript - Became a joint

• // // Single line Single line• /* … */ /* … */ Multiple line Multiple line

• There are still a few browsers in use that are so old There are still a few browsers in use that are so old that they do not recognize <script> tag. that they do not recognize <script> tag.

• These browsers will display the contents of the script These browsers will display the contents of the script elements as if it were just text.elements as if it were just text.

<script type = "javascript"> <script type = "javascript"> <!-- hide the script from other browsers<!-- hide the script from other browsers

javascript javascript

// stop hiding from other browsers -->// stop hiding from other browsers --></script> </script>

Comments in JavaScriptComments in JavaScript

Page 13: JavaScript. - Originally developed by Netscape, as LiveScript. - Became a joint venture of Netscape and Sun in 1995, renamed JavaScript - Became a joint

• Primitive Types: Primitive Types: 5 types5 types

• Number, String, Boolean, Undefined and null.Number, String, Boolean, Undefined and null.

numbersnumbers can be either integers or floating-point numbers. can be either integers or floating-point numbers.

Ex: 234, 4.5, 34.4, 7e2, etc.Ex: 234, 4.5, 34.4, 7e2, etc.

stringstring within either single or double quotes within either single or double quotes

Ex: ‘welcome’ , “India” , etc.Ex: ‘welcome’ , “India” , etc.

boolean boolean can be either can be either true true or or falsefalse

undefined undefined if a variable is declared and not assigned a value, it has the value if a variable is declared and not assigned a value, it has the value undefinedundefined. .

null null indicates no value. A variable is null if it has not been explicitly declared or indicates no value. A variable is null if it has not been explicitly declared or assigned a value.assigned a value.

Data typesData types

Page 14: JavaScript. - Originally developed by Netscape, as LiveScript. - Became a joint venture of Netscape and Sun in 1995, renamed JavaScript - Became a joint

• JavaScript is JavaScript is dynamically typeddynamically typed, that is, variables do , that is, variables do not have declared typesnot have declared types

• A variable cab be declared using the keyword - A variable cab be declared using the keyword - varvar

Ex:Ex:

var a = “web programming"; var a = “web programming"; // The value stored in a is of // The value stored in a is of string type. string type.

var b = 3;var b = 3; // The value stored in b has // The value stored in b has numeric type. numeric type.

var c = true;var c = true; // The value stored in c has Boolean // The value stored in c has Boolean type. type.

var d = 2.718281828;var d = 2.718281828; // The value stored in d has // The value stored in d has floating type.floating type.

Declaring VariablesDeclaring Variables

Page 15: JavaScript. - Originally developed by Netscape, as LiveScript. - Became a joint venture of Netscape and Sun in 1995, renamed JavaScript - Became a joint

• Numeric Operators :Numeric Operators :

Binary Operators: +, -, *, /, %Binary Operators: +, -, *, /, %

Unary operators: +, -, --, ++Unary operators: +, -, --, ++

Operator precedence:Operator precedence:

OperatorOperator AssociativityAssociativity

++, --, unary-, unary+ ++, --, unary-, unary+ RightRight

*, /, % *, /, % LeftLeft

+, - +, - leftleft

Numeric operatorsNumeric operators

Page 16: JavaScript. - Originally developed by Netscape, as LiveScript. - Became a joint venture of Netscape and Sun in 1995, renamed JavaScript - Became a joint

• The Math object allows you to perform mathematical The Math object allows you to perform mathematical tasks.tasks.

Mathematical constantsMathematical constants

PI - PI - Math.PIMath.PIsquare root of 2 - square root of 2 - Math.SQRT2Math.SQRT2square root of ½ - square root of ½ - Math.SQRT1_2Math.SQRT1_2natural log of 2 - natural log of 2 - Math.LN2Math.LN2natural log of 10 - natural log of 10 - Math.LN10Math.LN10base-2 log of E- base-2 log of E- Math.LOG2EMath.LOG2Ebase-10 log of E - base-10 log of E - Math.LOG10E Math.LOG10E

The The MathMath Object Object

Mathematical methods

Math.abs(-12); //Returns 12

Math.round(2.5); //Returns 3

Math.floor(5.6); //Returns 5

Math.max(2, 5, 9, 3); //Returns 9

Math.min(2, 5, 9, 3); //Returns 2

Math.pow(2, 5); //Returns 32

Math.random();

//Returns random number between 0 (inclusive) and 1 (exclusive)

Page 17: JavaScript. - Originally developed by Netscape, as LiveScript. - Became a joint venture of Netscape and Sun in 1995, renamed JavaScript - Became a joint

• The Number object includes the following collection of useful The Number object includes the following collection of useful properties. These properties are referenced through Number object.properties. These properties are referenced through Number object.

For Ex: NumberFor Ex: Number..MAX_VALUE, NumberMAX_VALUE, Number..MIN_VALUE, etc.MIN_VALUE, etc.

The The NumberNumber Object Object

Property Meaning

MAX_VALUE Largest representable number

MIN_VALUE Smallest representable number

NaN Not a Number

POSITIVE_INFINITY Special value to represent infinity.

NEGATIVE_ININITYNEGATIVE_ININITY Special value to represent –ve infinity.

PI The value of pi

Page 18: JavaScript. - Originally developed by Netscape, as LiveScript. - Became a joint venture of Netscape and Sun in 1995, renamed JavaScript - Became a joint

• If any arithmetic operation results in an error, it returns the value If any arithmetic operation results in an error, it returns the value NaN.NaN.

• Number object has a method: Number object has a method: toStringtoString. It converts a number to . It converts a number to string.string.

The String concatenation operator: The String concatenation operator:

It uses: It uses: ++ (plus) sign. (plus) sign.

Ex:Ex: “Welcome “ + “to NHCE”“Welcome “ + “to NHCE”

It results in the string:It results in the string: “Welcome to NHCE” “Welcome to NHCE”

The The NumberNumber Object (cont..) Object (cont..)

Page 19: JavaScript. - Originally developed by Netscape, as LiveScript. - Became a joint venture of Netscape and Sun in 1995, renamed JavaScript - Became a joint

JavaScript attempts to convert values automatically in order to JavaScript attempts to convert values automatically in order to

be able to perform operations.be able to perform operations.

““August “ + 1977 causes the number to be converted to string August “ + 1977 causes the number to be converted to string

and a concatenation to be performed. This results in the and a concatenation to be performed. This results in the

following string:following string:

“ “August 1977 “August 1977 “

var strValue = "4" + 3 + 1; var strValue = "4" + 3 + 1;

// becomes "431" // becomes "431"

var strValueTwo = 4 + 3 + "1"; var strValueTwo = 4 + 3 + "1";

// becomes “71”// becomes “71”

Implicit Type ConversionImplicit Type Conversion

Page 20: JavaScript. - Originally developed by Netscape, as LiveScript. - Became a joint venture of Netscape and Sun in 1995, renamed JavaScript - Became a joint

if you use operators other than +, the opposite type of conversion is if you use operators other than +, the opposite type of conversion is

applied—that is the string is converted to a number:applied—that is the string is converted to a number:

Ex: Ex:

7 * “3” causes the string to be converted to a number and a 7 * “3” causes the string to be converted to a number and a

multiplication to be performed resulting 21.multiplication to be performed resulting 21.

var firstResult = "35" - 3; var firstResult = "35" - 3;

// subtraction is applied, resulting in 32 // subtraction is applied, resulting in 32

var secondResult = 30 / "3"; var secondResult = 30 / "3";

// division is applied, resulting in 10 // division is applied, resulting in 10

var thirdResult = "3" * 3; var thirdResult = "3" * 3;

// multiplication is applied, resulting in 9// multiplication is applied, resulting in 9

Implicit Type Conversion (Cont..)Implicit Type Conversion (Cont..)

Page 21: JavaScript. - Originally developed by Netscape, as LiveScript. - Became a joint venture of Netscape and Sun in 1995, renamed JavaScript - Became a joint

• Several ways to force type conversions primarily between strings and numbers.Several ways to force type conversions primarily between strings and numbers.

• Numbers can be converted to Strings with the - Numbers can be converted to Strings with the - StringString constructor.constructor.Syntax: Syntax: Var str_value = String(value);Var str_value = String(value);

• This conversion could also be done with the This conversion could also be done with the toString()toString() method. method. The advantage here The advantage here is that it can be given a parameter to specify the base of the resulting number.is that it can be given a parameter to specify the base of the resulting number.Ex: Ex:

var num = 6;var num = 6;var str_value = var str_value = num.toString();num.toString();

// results in “6”// results in “6”var str_value_binary = var str_value_binary = num.toString(2)num.toString(2); ;

// results in “110” (binary)// results in “110” (binary)

• The The NumberNumber constructor can be used to convert a string to number. constructor can be used to convert a string to number.Syntax:Syntax:

var number = var number = Number(a string); Number(a string); // converts a string to number using Number // converts a string to number using Number constructor.constructor.var number = var number = a string - 0; a string - 0; // does the same thing as above// does the same thing as above

Ex: Ex: var n = var n = Number(“4”);Number(“4”); var number = var number = “4” - 0;“4” - 0;

Explicit type Conversion:Explicit type Conversion:

Page 22: JavaScript. - Originally developed by Netscape, as LiveScript. - Became a joint venture of Netscape and Sun in 1995, renamed JavaScript - Became a joint

• Js has 2 predefined string functions:Js has 2 predefined string functions:– parseIntparseInt and and parseFloatparseFloat

• They operate on strings given as parameters.They operate on strings given as parameters.

• ParseIntParseInt - Searches the string for an integer literal. If found at - Searches the string for an integer literal. If found at the the beginningbeginning of string it is converted to number and returned.of string it is converted to number and returned.

• If not found NaN is returned.If not found NaN is returned.

• ParseFloat-ParseFloat- Same as above, but it searches for floating point Same as above, but it searches for floating point literal, which could have a decimal point or an exponent or literal, which could have a decimal point or an exponent or both.both.

• In both cases, the numeric literal could be followed by any In both cases, the numeric literal could be followed by any non-digit character.non-digit character.

Explicit type Conversion: (Cont..)Explicit type Conversion: (Cont..)

Page 23: JavaScript. - Originally developed by Netscape, as LiveScript. - Became a joint venture of Netscape and Sun in 1995, renamed JavaScript - Became a joint

• Example:Example:

• parseInt(“3 blind mice”);parseInt(“3 blind mice”); // returns 3// returns 3• parseFloat(“3.14 meters”);parseFloat(“3.14 meters”); // returns 3.14// returns 3.14• parstInt(“12.34”);parstInt(“12.34”); // returns 12// returns 12• parstInt(“eleven”);parstInt(“eleven”); // returns NaN// returns NaN• parseFloat(“$55.5”);parseFloat(“$55.5”); // returns NaN// returns NaN

• We can also convert to numbers with the We can also convert to numbers with the eval()eval() method: method:• Ex:Ex:

– eval(“3.14”);eval(“3.14”); // returns 3.14;// returns 3.14;– eval(“2 * 3.14 * r”); eval(“2 * 3.14 * r”); // returns the result of the multiplication// returns the result of the multiplication– eval(“r > 3”);eval(“r > 3”); // returns true or false// returns true or false

Explicit type Conversion: (Cont..)Explicit type Conversion: (Cont..)

Page 24: JavaScript. - Originally developed by Netscape, as LiveScript. - Became a joint venture of Netscape and Sun in 1995, renamed JavaScript - Became a joint

• The operation + is the string concatenation operator.The operation + is the string concatenation operator.• In many cases, other types are automatically converted to In many cases, other types are automatically converted to

string.string.

String properties String properties ::

- - lengthlength: : (a property) (a property)Syntax: Syntax: var n = str1.length; var n = str1.length;

Example :Example :

// Returns 6 to // Returns 6 to lenlen

String (object) Properties and Methods:String (object) Properties and Methods:

Page 25: JavaScript. - Originally developed by Netscape, as LiveScript. - Became a joint venture of Netscape and Sun in 1995, renamed JavaScript - Became a joint

String methodsString methods::

- - charAtcharAt((positionposition)) str.charAt(3)str.charAt(3)

- - indexOfindexOf((stringstring)) str.indexOf(str.indexOf(''BB''))

- - substringsubstring((from, tofrom, to)) str.substring(1, 3)str.substring(1, 3)

- - toLowerCasetoLowerCase()() str.toLowerCase()str.toLowerCase()

- - toUpperCasetoUpperCase () () str.toUpperCase()str.toUpperCase()

Note:Note: In JavaScript, the subscript starts with 0. In JavaScript, the subscript starts with 0.

String (object) Properties and Methods: (Cont.)String (object) Properties and Methods: (Cont.)

Page 26: JavaScript. - Originally developed by Netscape, as LiveScript. - Became a joint venture of Netscape and Sun in 1995, renamed JavaScript - Became a joint

Examples :Examples :

String (object) Properties and Methods: (cont.)String (object) Properties and Methods: (cont.)

Page 27: JavaScript. - Originally developed by Netscape, as LiveScript. - Became a joint venture of Netscape and Sun in 1995, renamed JavaScript - Became a joint

The The typeof typeof OperatorOperator

• It returns the type of its single operand.It returns the type of its single operand.

• Returns “number” , “string” or “boolean” for primitive typesReturns “number” , “string” or “boolean” for primitive types

• Returns “object” for object or Returns “object” for object or nullnull type (objects do not have type (objects do not have types)types)

• Returns “undefined” if the operand is a variable that has Returns “undefined” if the operand is a variable that has not been assigned a value.not been assigned a value.

• Two syntactic forms:Two syntactic forms:

– typeof xtypeof x

– typeof(x)typeof(x)

Example:Example:

n=10;n=10;

document.write(“the data type is document.write(“the data type is “,typeof(n));“,typeof(n));

Page 28: JavaScript. - Originally developed by Netscape, as LiveScript. - Became a joint venture of Netscape and Sun in 1995, renamed JavaScript - Became a joint

The assignment statementsThe assignment statements

• The assignment operator that is used is:The assignment operator that is used is: = (equal = (equal symbol)symbol)

Example:Example:

1.1. c = a + b ;c = a + b ;

2.2. x = (a * b / c - d) * 2 ;x = (a * b / c - d) * 2 ;

3.3. a = a + 7 ;a = a + 7 ; or or a + = 7 ;a + = 7 ;

Page 29: JavaScript. - Originally developed by Netscape, as LiveScript. - Became a joint venture of Netscape and Sun in 1995, renamed JavaScript - Became a joint

The The DateDate Object: Object:

Used for date manipulation.

A Date object is created with the new operator and the Date constructor.

Ex:var today = new Date();

The Date object’s methods can be used retrieve information from it.

Page 30: JavaScript. - Originally developed by Netscape, as LiveScript. - Became a joint venture of Netscape and Sun in 1995, renamed JavaScript - Became a joint

The The DateDate Object: Methods Object: Methods

toLocaleString A string of the Date information

getDate The day of the month

getMonth The month of the year, as a number in the range of 0 to 11

getDay The day of the week, as a number in the range of 0 to 6

getFullYear The year

getTime The number of milliseconds since January 1, 1970

getHours The number of the hour, as a number in the range of 0 to 23

getMinutes The number of the minute, as a number in the range of 0 to 59

getSecondsThe number of the second, as a number in the range of 0 to 59

getMillisecondsThe number of the millisecond, as a number in the range of 0 to 999

Method Meaning

Page 31: JavaScript. - Originally developed by Netscape, as LiveScript. - Became a joint venture of Netscape and Sun in 1995, renamed JavaScript - Became a joint

Example:Example:

A program to illustrate usage of date object’s methods:A program to illustrate usage of date object’s methods:

<! DOCTYPE HTML PUBLIC "-//w3c//DTD xHTML 1.1//EN" <! DOCTYPE HTML PUBLIC "-//w3c//DTD xHTML 1.1//EN"

"//http://www.w3.org/TR/xhtml/11/DTD/xhtml 11.DTD">"//http://www.w3.org/TR/xhtml/11/DTD/xhtml 11.DTD">

<html xmlns="www.w3.org/tr/xhtml/1999/xhtml1.dtd"><html xmlns="www.w3.org/tr/xhtml/1999/xhtml1.dtd">

<body><body>

<h2 style='color:red'>DATE OBJECT METHODS: </h2><h2 style='color:red'>DATE OBJECT METHODS: </h2>

<script type="text/javascript" src=“date.js”><script type="text/javascript" src=“date.js”>

</script></script>

</body></body>

</html></html>

Page 32: JavaScript. - Originally developed by Netscape, as LiveScript. - Became a joint venture of Netscape and Sun in 1995, renamed JavaScript - Became a joint
Page 33: JavaScript. - Originally developed by Netscape, as LiveScript. - Became a joint venture of Netscape and Sun in 1995, renamed JavaScript - Became a joint
Page 34: JavaScript. - Originally developed by Netscape, as LiveScript. - Became a joint venture of Netscape and Sun in 1995, renamed JavaScript - Became a joint

Js uses Js uses DocumentDocument object to refer to current XHTML document.object to refer to current XHTML document.

Js uses Js uses WindowWindow object to refer to the window in which XHTML object to refer to the window in which XHTML document is displayed. document is displayed.

The The WindowWindow object has two properties:object has two properties: documentdocument and and windowwindow..

The The documentdocument property refers to the property refers to the DocumentDocument object.object.

The The windowwindow property is self referential. i.e., it refers to the property is self referential. i.e., it refers to the WindowWindow object.object.

DocumentDocument object has several properties and methods. one object has several properties and methods. one important method is: important method is: writewrite..

writewrite used to create script output on the screen. used to create script output on the screen.

Ex: Ex: document.write(“ The result is: “, result, “<br />”); document.write(“ The result is: “, result, “<br />”);

Screen Output and Keyboard InputScreen Output and Keyboard Input

Page 35: JavaScript. - Originally developed by Netscape, as LiveScript. - Became a joint venture of Netscape and Sun in 1995, renamed JavaScript - Became a joint

Methods of Window ObjectMethods of Window Object

The The Window Window object includes 3 methods that object includes 3 methods that create dialog boxes for three kinds of user create dialog boxes for three kinds of user interactions.interactions.

The default object of Js is the The default object of Js is the Window Window object, so calls to the methods need not object, so calls to the methods need not include object reference.include object reference.

Page 36: JavaScript. - Originally developed by Netscape, as LiveScript. - Became a joint venture of Netscape and Sun in 1995, renamed JavaScript - Became a joint

The alert MethodThe alert Method

1. alert method:1. alert method: The alert method opens a dialog box The alert method opens a dialog box with a message.with a message.

• The output of the alert is The output of the alert is notnot XHTML, so use new lines XHTML, so use new lines rather than <br/>rather than <br/>

• Ex:Ex: alert("The sum is:" + sum + "\n");alert("The sum is:" + sum + "\n");

Output:Output:

Page 37: JavaScript. - Originally developed by Netscape, as LiveScript. - Became a joint venture of Netscape and Sun in 1995, renamed JavaScript - Became a joint

• The confirm methods displays a message provided as a parameterThe confirm methods displays a message provided as a parameter– The confirm dialog has two buttons: The confirm dialog has two buttons: OKOK and and CancelCancel

• If the user presses OK, If the user presses OK, truetrue is returned by the method is returned by the method• If the user presses Cancel, If the user presses Cancel, falsefalse is returned is returned

Example:Example:

2. The confirm Method2. The confirm Method

var question =confirm("Do you want to continue this download?");

Page 38: JavaScript. - Originally developed by Netscape, as LiveScript. - Became a joint venture of Netscape and Sun in 1995, renamed JavaScript - Became a joint

• This method displays its string argument in a dialog boxThis method displays its string argument in a dialog box– A second argument provides a default content for the user entry A second argument provides a default content for the user entry

areaarea

• The dialog box has an area for the user to enter textThe dialog box has an area for the user to enter text• The method returns a String with the text entered by the userThe method returns a String with the text entered by the user

Example:Example:

3. The prompt Method3. The prompt Method

name = prompt("What is your name?", "");

Page 39: JavaScript. - Originally developed by Netscape, as LiveScript. - Became a joint venture of Netscape and Sun in 1995, renamed JavaScript - Became a joint

• Example:Example:• A program to find the roots of a quadratic equationA program to find the roots of a quadratic equation

• Type the following program in the file:Type the following program in the file: roots.htmlroots.html

Page 40: JavaScript. - Originally developed by Netscape, as LiveScript. - Became a joint venture of Netscape and Sun in 1995, renamed JavaScript - Became a joint

• Example:Example: (Cont..)(Cont..)

Type the below script in the file: roots.jsType the below script in the file: roots.js

Page 41: JavaScript. - Originally developed by Netscape, as LiveScript. - Became a joint venture of Netscape and Sun in 1995, renamed JavaScript - Became a joint

They alter the flow of control in a program. They alter the flow of control in a program. They contain control expressions.They contain control expressions.

The result of evaluating a control expression The result of evaluating a control expression is one of the Boolean values: is one of the Boolean values: truetrue or or falsefalse..

Control StatementsControl Statements

Page 42: JavaScript. - Originally developed by Netscape, as LiveScript. - Became a joint venture of Netscape and Sun in 1995, renamed JavaScript - Became a joint

Relational operatorsRelational operators

OperationOperation OperatorOperator

• Is equal to Is equal to = == =

• Is not equal to Is not equal to !=!=

• Is less than Is less than <<

• Is greater than Is greater than >>

• Is less than or equal to Is less than or equal to <=<=

• Is greater than or equal to Is greater than or equal to >=>=

• Is strictly equal to Is strictly equal to = = == = =

• Is strictly not equal to Is strictly not equal to ! = =! = =

Page 43: JavaScript. - Originally developed by Netscape, as LiveScript. - Became a joint venture of Netscape and Sun in 1995, renamed JavaScript - Became a joint

The operators === and !== disallow type conversion of either The operators === and !== disallow type conversion of either operand.operand.

The expression “3” === 3 The expression “3” === 3

evaluates to evaluates to falsefalse

where as “3” == 3where as “3” == 3

evaluates to evaluates to truetrue

Logical Operators:Logical Operators:

OperationOperation OperatorOperator

ANDAND &&&&

OROR ||||

NOTNOT !!

Examples:Examples:

Page 44: JavaScript. - Originally developed by Netscape, as LiveScript. - Became a joint venture of Netscape and Sun in 1995, renamed JavaScript - Became a joint

switch Statementswitch Statement

Syntax:

switch (expression) {

case value_1: statement(s)

case value_2: statement(s)

...

[default: statement(s)]

}

Page 45: JavaScript. - Originally developed by Netscape, as LiveScript. - Became a joint venture of Netscape and Sun in 1995, renamed JavaScript - Became a joint

• The expression is evaluated.The expression is evaluated.• The value of the expressions is compared to the value The value of the expressions is compared to the value

in each case.in each case.• If no case matches, execution begins at the default If no case matches, execution begins at the default

case.case.• Otherwise, execution continues with the statement Otherwise, execution continues with the statement

following the case.following the case.• Execution continues until either the end of the switch Execution continues until either the end of the switch

is encountered or a is encountered or a breakbreak statement is executed. statement is executed.

Working of switch Statement:Working of switch Statement:

Page 46: JavaScript. - Originally developed by Netscape, as LiveScript. - Became a joint venture of Netscape and Sun in 1995, renamed JavaScript - Became a joint

Example:Example:

Page 47: JavaScript. - Originally developed by Netscape, as LiveScript. - Became a joint venture of Netscape and Sun in 1995, renamed JavaScript - Became a joint
Page 48: JavaScript. - Originally developed by Netscape, as LiveScript. - Became a joint venture of Netscape and Sun in 1995, renamed JavaScript - Became a joint

Selection Statements are similar to those of C, Java and Selection Statements are similar to those of C, Java and c++.c++.

Example:Example:

Selection Statement:Selection Statement:

Page 49: JavaScript. - Originally developed by Netscape, as LiveScript. - Became a joint venture of Netscape and Sun in 1995, renamed JavaScript - Became a joint

• Loop statements in JavaScript are similar to those in C/C++/Java.Loop statements in JavaScript are similar to those in C/C++/Java.

While loop:While loop:

while (while (control expressioncontrol expression)){{

statements;statements;}}

• For loop:For loop:

for (for (initial exp; control exp; increment exp)initial exp; control exp; increment exp){{

statements;statements;}}

• do/while loop:do/while loop:

do do {{

statements;statements;} while (} while (control expressioncontrol expression););

Loop StatementsLoop Statements

Page 50: JavaScript. - Originally developed by Netscape, as LiveScript. - Became a joint venture of Netscape and Sun in 1995, renamed JavaScript - Became a joint

• If the control expression is true, then the statement is executedIf the control expression is true, then the statement is executed

• This will be repeated until the control expression becomes falseThis will be repeated until the control expression becomes false

Example:Example:

<script type="text/javascript"><script type="text/javascript">

i=0;i=0;

while (i<=5)while (i<=5)

{{

document.write("The document.write("The number is " + i);number is " + i);

document.write("<br />");document.write("<br />");

i++;i++;

}}</script></script>

whilewhile Statement Example: Statement Example:

Page 51: JavaScript. - Originally developed by Netscape, as LiveScript. - Became a joint venture of Netscape and Sun in 1995, renamed JavaScript - Became a joint

• If the control expression is true, the statement is executed.If the control expression is true, the statement is executed.• Then the increment expression is evaluated.Then the increment expression is evaluated.• When the control expression becomes false, it terminates the When the control expression becomes false, it terminates the

loop..loop..

Example:Example:

<script type="text/javascript"><script type="text/javascript">

for (var i = 0; i <= 5; i++)for (var i = 0; i <= 5; i++)

{{

document.write("The number document.write("The number is " + i);is " + i);

document.write("<br />");document.write("<br />");

}}

</script></script>

forfor Statement Example: Statement Example:

Page 52: JavaScript. - Originally developed by Netscape, as LiveScript. - Became a joint venture of Netscape and Sun in 1995, renamed JavaScript - Became a joint

• The The newnew expression is used to create an object expression is used to create an object

– This includes a call to a This includes a call to a constructorconstructor– The new operator creates a blank object, The new operator creates a blank object,

the constructor creates and initializes all the constructor creates and initializes all properties of the objectproperties of the object

• Properties of an object are accessed using a dot Properties of an object are accessed using a dot notation: notation: object object . . propertyproperty

• Properties are not variables, so they are not Properties are not variables, so they are not declared.declared.

Object Creation and ModificationObject Creation and Modification

Page 53: JavaScript. - Originally developed by Netscape, as LiveScript. - Became a joint venture of Netscape and Sun in 1995, renamed JavaScript - Became a joint

The number of properties in a Js object is The number of properties in a Js object is dynamicdynamic..

Properties can be added to or deleted from an object at any point Properties can be added to or deleted from an object at any point of time during interpretation.of time during interpretation.

A property for an object can be created simply by assigning a A property for an object can be created simply by assigning a value to that property.value to that property.

// Create an Object Car// Create an Object Carvar my_car = new Object();var my_car = new Object();

// Create and initialize the make property// Create and initialize the make propertymy_car.make = "Ford";my_car.make = "Ford";

// Create and initialize model// Create and initialize modelmy_car.model = "Contour SVT";my_car.model = "Contour SVT";

• The delete operator can be used to delete a property from an The delete operator can be used to delete a property from an object.object.Ex:Ex: delete my_car.modeldelete my_car.model

Creation or Deletion of Object Creation or Deletion of Object PropertiesProperties

Page 54: JavaScript. - Originally developed by Netscape, as LiveScript. - Became a joint venture of Netscape and Sun in 1995, renamed JavaScript - Became a joint

• Used for listing the properties of an object.Used for listing the properties of an object.

forfor (identifier (identifier inin object) object)

statement or compound statement;statement or compound statement;

Example:Example:

for for (var prop (var prop in in my_car)my_car)

document.write(“Name: “,prop, “Value: “, document.write(“Name: “,prop, “Value: “, my_car[prop]);my_car[prop]);

• The variable prop takes on the values of the properties of the The variable prop takes on the values of the properties of the my_car object, one for each iteration.my_car object, one for each iteration.

• This code will list all of the values of the properties of my_car.This code will list all of the values of the properties of my_car.

The The for-infor-in Statement: Statement:

Page 55: JavaScript. - Originally developed by Netscape, as LiveScript. - Became a joint venture of Netscape and Sun in 1995, renamed JavaScript - Became a joint

ArraysArrays

Page 56: JavaScript. - Originally developed by Netscape, as LiveScript. - Became a joint venture of Netscape and Sun in 1995, renamed JavaScript - Became a joint

• An array is a special variable, which can hold more than one An array is a special variable, which can hold more than one value, at a time under a single name.value, at a time under a single name.

Characteristics of Characteristics of Array ObjectsArray Objects : :

• You can access the values by referring to the array name with You can access the values by referring to the array name with numeric subscript expressions placed in brackets..numeric subscript expressions placed in brackets..

• Array indexes in JavaScript begin at 0Array indexes in JavaScript begin at 0

• lengthlength property can be used for property can be used for fetching fetching or or setting setting the size of the size of the array.the array.

• Js arrays have Js arrays have dynamic length.dynamic length. (that means, all array elements (that means, all array elements are allocated dynamically from the heap.)are allocated dynamically from the heap.)

ArraysArrays

Page 57: JavaScript. - Originally developed by Netscape, as LiveScript. - Became a joint venture of Netscape and Sun in 1995, renamed JavaScript - Became a joint

• The length of an array is the highest subscript to The length of an array is the highest subscript to which a value has been assigned, plus 1.which a value has been assigned, plus 1.

• The length of an array can be set to any value by The length of an array can be set to any value by using the length property, as in the following example:using the length property, as in the following example:

my_list.length = 1002;my_list.length = 1002;

Now, the length of my_list is 1002, regardless of what Now, the length of my_list is 1002, regardless of what it was previously. it was previously.

Characteristics of Characteristics of Array Objects Array Objects (Cont.)(Cont.)

Page 58: JavaScript. - Originally developed by Netscape, as LiveScript. - Became a joint venture of Netscape and Sun in 1995, renamed JavaScript - Became a joint

• An array can be defined in three ways. An array can be defined in three ways.

• The following code creates an Array object called myCars: The following code creates an Array object called myCars:

var myCars = new Array(); var myCars = new Array(); myCars[0] = “Hyundai“ ;       myCars[0] = “Hyundai“ ;       myCars[1] = “Volvo“ ;myCars[1] = “Volvo“ ;myCars[2] = “BMW“ ; myCars[2] = “BMW“ ;

• var myCars = new Array(“Hyundai","Volvo","BMW"); var myCars = new Array(“Hyundai","Volvo","BMW");

• var myCars = [“Hyundai","Volvo","BMW"]; var myCars = [“Hyundai","Volvo","BMW"];

ArrayArray Object Creation Object Creation

Regular array

condensed array

Literal array

Page 59: JavaScript. - Originally developed by Netscape, as LiveScript. - Became a joint venture of Netscape and Sun in 1995, renamed JavaScript - Became a joint

Examples: (Cont.)Examples: (Cont.)

1.1.

2.2.

3.3.

Note:Note: The elements of the array need not have the The elements of the array need not have the same type in Javascript.same type in Javascript.

Page 60: JavaScript. - Originally developed by Netscape, as LiveScript. - Became a joint venture of Netscape and Sun in 1995, renamed JavaScript - Became a joint

<script type="text/javascript"><script type="text/javascript">var x;var x;var mycars = new Array();var mycars = new Array();mycars[0] = "Spark";mycars[0] = "Spark";mycars[1] = "Volvo";mycars[1] = "Volvo";mycars[2] = "BMW";mycars[2] = "BMW";

for (x in mycars)for (x in mycars){{

document.write(mycars[x] + "<br />");document.write(mycars[x] + "<br />");}}

</script></script>

Example: Example: (using the for-in Loop):(using the for-in Loop):

Page 61: JavaScript. - Originally developed by Netscape, as LiveScript. - Became a joint venture of Netscape and Sun in 1995, renamed JavaScript - Became a joint

1. Join1. Join - The join() method joins all elements of an array into a - The join() method joins all elements of an array into a string, and returns the string.string, and returns the string.

• Example:Example:

• The value of The value of name_stringname_string is now is now “Mary : Murray : Murphy “Mary : Murray : Murphy : Max”: Max”

2. Sort 2. Sort – – Sorts the content in order.Sorts the content in order.

• Example:Example:

• The value of The value of namesnames is now is now [“Mary”, “Max”, “Murphy”, “Murray”][“Mary”, “Max”, “Murphy”, “Murray”]

ArrayArray Methods Methods

Page 62: JavaScript. - Originally developed by Netscape, as LiveScript. - Became a joint venture of Netscape and Sun in 1995, renamed JavaScript - Became a joint

3. Reverse3. Reverse - The reverse() method reverses the order - The reverse() method reverses the order of the elements in an arrayof the elements in an array

4. Concat 4. Concat – – joins its parameters to the end of the Array joins its parameters to the end of the Array object on which it is called.object on which it is called.

• Example: Example:

• The The new_namesnew_names array now has length 6, with the array now has length 6, with the elements of names, along with “Moo” and “Meow”, as elements of names, along with “Moo” and “Meow”, as its fifth and sixth elements.its fifth and sixth elements.

ArrayArray Methods (Cont.) Methods (Cont.)

Page 63: JavaScript. - Originally developed by Netscape, as LiveScript. - Became a joint venture of Netscape and Sun in 1995, renamed JavaScript - Became a joint

5. Slice5. Slice – – The slice() method extracts a part of a array The slice() method extracts a part of a array and returns the extracted part in a new array. and returns the extracted part in a new array.

• Example:Example:

• The value of The value of list2list2 is now [4, 6] is now [4, 6]

• Note:Note: The array returned has the elements of the The array returned has the elements of the Array object, from the first parameter up to, but not Array object, from the first parameter up to, but not including, the second parameter.including, the second parameter.

ArrayArray Methods (Cont.) Methods (Cont.)

Page 64: JavaScript. - Originally developed by Netscape, as LiveScript. - Became a joint venture of Netscape and Sun in 1995, renamed JavaScript - Became a joint

• The below methods are used for Dynamic List Operations The below methods are used for Dynamic List Operations (implementation on Stacks and Queues)(implementation on Stacks and Queues)

6. push6. push– Add the content to the end of an arrayAdd the content to the end of an array– arrayarray.push(ele1, ele2, ..., ele X).push(ele1, ele2, ..., ele X)

7. pop7. pop– Remove the content from the end of an arrayRemove the content from the end of an array– arrayarray.pop().pop()

Example:Example:

ArrayArray Methods (Cont.) Methods (Cont.)

Page 65: JavaScript. - Originally developed by Netscape, as LiveScript. - Became a joint venture of Netscape and Sun in 1995, renamed JavaScript - Became a joint

8. shift8. shift– Remove the content from the front of an arrayRemove the content from the front of an array– arrayarray.shift().shift()

9. unshift9. unshift– Add the content to the front of an arrayAdd the content to the front of an array– arrayarray.unshift(element1,element2, ..., elementX) .unshift(element1,element2, ..., elementX)

Example:Example:

ArrayArray Methods (Cont.) Methods (Cont.)

Page 66: JavaScript. - Originally developed by Netscape, as LiveScript. - Became a joint venture of Netscape and Sun in 1995, renamed JavaScript - Became a joint

Example: for a two-dimensional array (or array Example: for a two-dimensional array (or array of arrays or nested arrays) implementation:of arrays or nested arrays) implementation:

Page 67: JavaScript. - Originally developed by Netscape, as LiveScript. - Became a joint venture of Netscape and Sun in 1995, renamed JavaScript - Became a joint

Output:Output:

Page 68: JavaScript. - Originally developed by Netscape, as LiveScript. - Became a joint venture of Netscape and Sun in 1995, renamed JavaScript - Became a joint

Refer Javascript Part-2