Presentation is loading. Please wait.

Presentation is loading. Please wait.

JavaScript, by Dr. Khalil1 JavaScript Dr. Awad Khalil Computer Science Department AUC.

Similar presentations


Presentation on theme: "JavaScript, by Dr. Khalil1 JavaScript Dr. Awad Khalil Computer Science Department AUC."— Presentation transcript:

1 JavaScript, by Dr. Khalil1 JavaScript Dr. Awad Khalil Computer Science Department AUC

2 JavaScript, by Dr. Khalil2 Content  Introduction  Uses of JavaScript  Incorporating JavaScript in Documents  Basic JavaScript Syntax  Datatypes & Variables  JavaScript Arithmetic operators  JavaScript Assignment operators  JavaScript Comparison Operators  JavaScript Logical Operators  JavaScript string Operators & Tokens  Control Structures

3 JavaScript, by Dr. Khalil3 Introduction  is a technology which facilitates a disciplined approach to designing computer programs that enhance the functionality and appearance of Web pages.  JavaScript scripting language, is a technology which facilitates a disciplined approach to designing computer programs that enhance the functionality and appearance of Web pages.  JavaScript was originally created by Netscape in 1996, while Microsoft’s version of JavaScript is called Jscript.  Despite its naming, JavaScript is not Java. It inherited the moniker “Java” due to many similarities with Sun’s Java language.

4 JavaScript, by Dr. Khalil4 Uses for JavaScript   It is a client-based language.   It is a scripting language with definite limitations.  JavaScript can parse form data prior to the data being submitted to the server, ensuring that there are no obvious errors (missing or improperly formatted data).  Data verification: JavaScript can parse form data prior to the data being submitted to the server, ensuring that there are no obvious errors (missing or improperly formatted data).  : Accessing element data and properties via the DOM, JavaScript can affect changes in elements’ content, appearance, size, position, and so forth.  Document animation and automation : Accessing element data and properties via the DOM, JavaScript can affect changes in elements’ content, appearance, size, position, and so forth.  : JavaScript can initiate changes in documents based on other dynamic criteria..  Basic Document Intelligence : JavaScript can initiate changes in documents based on other dynamic criteria..

5 JavaScript, by Dr. Khalil5 Incorporating JavaScrip in Documents  The most popular method of incorporating JavaScript in documents is by enclosing the scripts within tags with the following syntax: …. Script content ….  Current versions of XHTML support the following Multipurpose Internet Mail Extensions (MIME) types for the tag:  text/ecmascript  text/javascript  text/jscript  text/vbscript  text/vbs  text/xml

6 JavaScript, by Dr. Khalil6 Optional Attributes in tag AttributeValue(s)Use charset charset code Defines the character encoding used in the script deferdefer Informs the user agent that the script will not generate content, and document processing (rendering) can continue without waiting to evaluate the script content. srcURL Instructs the user agent to incorporate the contents of the document found at the specified URL as the script content.

7 JavaScript, by Dr. Khalil7 Placement of the Script Tag  Technically, the script tag should be placed within the section of the document where it can be easily located.  However, in practice we can place the tag anywhere within the document.  That said, the tag should always appear within a block element.

8 JavaScript, by Dr. Khalil8 Execution of Scripts  Unless otherwise instructed, user agents execute JavaScript code as soon as it is encountered in a document. The exceptions to this rule include the following  Scripting being disabled in the user agent.  The defer attribute being set in the tag.  All code being contained within functions that are not explicitly called during the document’s rendering.  We can force a script to run immediately after the document is loaded by using the onload event in the tag: function runmelater() { function runmelater() { // script code // script code }</script></head><body><p> // script code (not enclosed in function(s)) // script code (not enclosed in function(s)) </p></body><html>

9 JavaScript, by Dr. Khalil9 Basic JavaScript Syntax  JavaScript follows fairly basic syntax that can be outlined with a few simple rules:  All code should appear within appropriate constructs, namely between tags or within event attributes.  With few exceptions, code lines should end with a semicolon (;). Notable exceptions to this rule are lines that end in a block delimiter ({ or }).  Blocks of code (usually under control structures such as functions, if statements, and so on) are enclosed in braces ({ and }).  Although it is not absolutely necessary, explicit declaration of all variables is a good idea.  The use of functions to delimit code fragments is recommended.  Comments can be inserted in JavaScript code by prefixing the comment with a double-slash (//) or surrounded the comment with /* and */ pairs

10 JavaScript, by Dr. Khalil10 Data Types and Variables  JavaScript, like most other programming languages, supports a wide range of data types. However, JavaScript employs little data type checking. JavaScript supports the following data types:  Booleans  Integers  Floating –point numbers  Strings  Arrays  Examples: a = new Array(); months = new (“JAN”, “FEB”, “MAR, “APR”, “MAY, “JUN”, “JUL”, …, “DEC”); months = new (“JAN”, “FEB”, “MAR, “APR”, “MAY, “JUN”, “JUL”, …, “DEC”); s = new String (); s = new String (); n = new Number (); n = new Number ();

11 JavaScript, by Dr. Khalil11 Variables  JavaScript variables are case sensitive and can contain a mix of letters and numbers.  JavaScript uses the var statement to explicitly declare variables,  Examples: var x; var x = 20; var x = 20; var x = 20, Lastname = ‘Khalil’; var x = 20, Lastname = ‘Khalil’;  JavaScript variables have global scope unless they are declared within a function.  For example, in the following code the variable x is global while variable y is local to the function: var x = 100; var x = 100; function spacefill(text, amount) { function spacefill(text, amount) { var y = 0; var y = 0; … }</script>

12 JavaScript, by Dr. Khalil12 Simple Examples – First Program in JavaScript A First Program in JavaScript document.writeln(“ Welcome to JavaScript Programming! ”);

13 JavaScript, by Dr. Khalil13 Example 2 – Printing on one line A First Program in JavaScript document.write( “ Welcome to “ document.writeln(“JavaScript Programming! ”);

14 JavaScript, by Dr. Khalil14 Example 3 – Printing on multiple lines Printing Multiple Lines document.writeln(“ Welcome to JavaScript Programming! ”);

15 JavaScript, by Dr. Khalil15 Example 4 – Displaying multiple lines in a dialog box Printing Multiple Lines window.alert(“Welcome to\nJavaScript\nProgramming!”);

16 JavaScript, by Dr. Khalil16 JavaScript Arithmetic Operators OperatorUse +Addition -Subtraction *Multiplication /Division %Modulus ++Increment --Decrement

17 JavaScript, by Dr. Khalil17 JavaScript Assignment Operators OperatorUse =Assignment += Increment assignment -= Decrement assignment *= Multiplication assignment /= Division assignment %= Modulus assignment

18 JavaScript, by Dr. Khalil18 Assignment Operators Assignment Operator Initial variable Value Sample expression ExplanationASSIGNS += c = 3c += 7c = c + 710 to c -= d = 5d -= 4d = d – 41 to d *= e = 4e *= 5e = e * 520 to e /= f = 6f /= 3f = f / 32 to f %= g = 12g %= 9g = g % 93 to g

19 JavaScript, by Dr. Khalil19 Example 5 – Adding Integers An Addition Program var firstNumber,// first string entered by user secondNumber, // second string entered by user number1,// first number to add number2,// second number to add sum;// sum of number1 and number2 // read in first number from user as string firstNumber = window.prompt( “Enter first integer”, “0’ ); // read in second number from user as string secondNumber = window.prompt( “Enter second integer”, “0’ ); // convert numbers from strings to integers number1 = parseInt(firstNumber); number2 = parseInt(secondNumber); // add the numbers sum = number1 + number2; // display the results document.writeln( “ The sum is “ + sum + “ ”);

20 JavaScript, by Dr. Khalil20 Example 5 – Adding Integers

21 JavaScript, by Dr. Khalil21 JavaScript Comparison Operators OperatorUse == Is equal to === Exactly equal to – in value and type != Is not equal to > Is greater than < Is less than >= Is greater than or equal to <= Is less than or equal to

22 JavaScript, by Dr. Khalil22 JavaScript Logical Operators OperatorUse &&And ││Or !Not

23 JavaScript, by Dr. Khalil23 Demonstrating the Logical Operators Demonstrating the logical operators Demonstrating the logical operators document.writeln( " " ); document.writeln( " Logical AND (&&) " + " Logical AND (&&) " + " false && false: " + ( false && false ) + " false && false: " + ( false && false ) + " false && true: " + ( false && true ) + " false && true: " + ( false && true ) + " true && false: " + ( true && false ) + " true && false: " + ( true && false ) + " true && true: " + ( true && true ) + " " ); " true && true: " + ( true && true ) + " " ); document.writeln( document.writeln( " Logical OR (||) " + " Logical OR (||) " + " false || false: " + ( false || false ) + " false || false: " + ( false || false ) + " false || true: " + ( false || true ) + " false || true: " + ( false || true ) + " true || false: " + ( true || false ) + " true || false: " + ( true || false ) + " true || true: " + ( true || true ) + " " ); " true || true: " + ( true || true ) + " " ); document.writeln( document.writeln( " Logical NOT (!) " + " Logical NOT (!) " + " !false: " + ( !false ) + " !false: " + ( !false ) + " !true: " + ( !true ) + " " ); " !true: " + ( !true ) + " " ); doccument.writeln( " " ); </SCRIPT></HEAD><BODY></BODY></HTML>

24 JavaScript, by Dr. Khalil24

25 JavaScript, by Dr. Khalil25 JavaScript String Operators OperatorUse +Concatenation

26 JavaScript, by Dr. Khalil26 JavaScript String Tokens TokenCharacter \\Backslash \’ Single quote \” Double quote \bBackspace \f Form Feed \n Line Feed \r Carriage Return \t Horizontal Tab \v Vertical Tab

27 JavaScript, by Dr. Khalil27 Control Structures if structure if ( ) { // statement(s) to execute if condition is true } [ else { // statement(s) to execute if condition is false }]

28 JavaScript, by Dr. Khalil28 Control Structures (Cont’d) if structure if ( studentGrade >= 60 ) document.writeln ( “Passed” ); If else structure if ( studentGrade >= 60 ) document.writeln ( “Passed” ); else document.writeln ( “Failed” ); --------------------------------------------------------------------------------------------------- if ( studentGrade >= 60 ) document.writeln ( “Passed” ); else { document.writeln ( “Failed ” ); document.writeln ( “You must repeat this course” ); }

29 JavaScript, by Dr. Khalil29 Control Structures (Cont’d) Nested-if structure if ( studentGrade >= 90 ) document.writeln ( “A” ); else if ( studentGrade >= 80 ) document.writeln ( “B” ); else if ( studentGrade >= 70 ) document.writeln ( “C” ); else if ( studentGrade >= 60 ) document.writeln ( “D” ); else document.writeln ( “F” );

30 JavaScript, by Dr. Khalil30 Control Structures switch structure switch ( gradeLetter ) { case “A”: case “a”: gradeName = “Excellent; break; case “B”: case “b”: gradeName = “Very Good”; break; case “C”: case “c”: gradeName = “Good”; break; case “D”: case “d”: gradeName = “Sufficient”; break; case “F”: case “f”: gradeName = “Fail”; break; default: gradeName = “Invalid grade”; }

31 JavaScript, by Dr. Khalil31 Decision Making – An Example Performing Comparisons var first,// first string entered by user second, // second string entered by user // read in first number from user as string first = window.prompt( “Enter first integer:”, “0’ ); // read in second number from user as string second = window.prompt( “Enter second integer:”, “0’ ); document.writeln( “ Comparison Results ” ); document.writeln( “ ” ); if ( first == second ) document.writeln( “ ” + first + “ == “ + second + “ ” ); if ( first != second ) document.writeln( “ ” + first + “ != “ + second + “ ” ); if ( first > second ) document.writeln( “ ” + first + “ > “ + second + “ ” ); if ( first >= second ) document.writeln( “ ” + first + “ >= “ + second + “ ” ); if ( first < second ) document.writeln( “ ” + first + “ ” ); if ( first <= second ) document.writeln( “ ” + first + “ >= “ + second + “ ” ); document.writeln( “ ” );

32 JavaScript, by Dr. Khalil32

33 JavaScript, by Dr. Khalil33

34 JavaScript, by Dr. Khalil34 Repetition Structures – while Loop while while ( ) { // statement(s) to execute }; Examples var product = 2; while ( product <= 100 ) product = product * 2; ------------------------------- var counter = 1 while ( counter <= 30 ) { sum = sum + score; counter = counter + 1; } ----------------------------------

35 JavaScript, by Dr. Khalil35 Repetition - Counter-controlled while loop <HEAD> Counter-controlled loops Counter-controlled loops var counter = 1;// initialize the counter while ( counter <= 7 )// loop condition { document.writeln( " HTML font size " + document.writeln( " HTML font size " + counter + " " ); counter + " " ); ++counter;// increment ++counter;// increment }</SCRIPT></HEAD><BODY></BODY></HTML>

36 JavaScript, by Dr. Khalil36

37 JavaScript, by Dr. Khalil37 Counter-controlled loop – An Example Class Average Program Class Average Program var total,// sum of grades gradeCounter,// number of grades entered gradeCounter,// number of grades entered gradeValue,// grade value gradeValue,// grade value average,// average of all grades average,// average of all grades grade;// grade typed by uesr grade;// grade typed by uesr // initialization phase total = 0;// clear total gradeCounter = 1;// initialize the counter // processing phase while ( gradeCounter <= 10 ) { grade = window.prompt ( "Enter integer grade:", "0" ); grade = window.prompt ( "Enter integer grade:", "0" ); gradeValue = parseInt( grade ); gradeValue = parseInt( grade ); total = total + gradeValue; total = total + gradeValue; gradeCounter = gradeCounter + 1; gradeCounter = gradeCounter + 1;} average = total / 10; document.writeln( " Class average is " + average + " " ); </SCRIPT> Refresh to run the script again Refresh to run the script again </HTML>

38 JavaScript, by Dr. Khalil38

39 JavaScript, by Dr. Khalil39 Repetition Structures – do while Loop do while do { // statement(s) to execute }While ( ); Examples X = 0; do { x++; // increment x } while (x < 20);

40 JavaScript, by Dr. Khalil40 The do/while loop<HTML><HEAD> Using the do/while loop Using the do/while loop var counter = 1; do { document.writeln( " This is an H" + counter + " level head" + " This is an H" + counter + " level head" + "</H" + counter + ">" ); counter + ">" ); ++ counter; ++ counter; } while ( counter <= 6 ); </SCRIPT></HEAD><BODY></BODY></HTML>

41 JavaScript, by Dr. Khalil41 for loop General Format: ( initialization; loopContinuationTest; increment ) for ( initialization; loopContinuationTest; increment )statement---------------------------------------------------------------------------------------------------------------<HTML><HEAD> Counter-controlled loops Counter-controlled loops // Initialization, loop condition and incrementing // are all included in the for structure header. for ( var counter = 1; counter <= 7; ++counter ) document.writeln( " HTML font size " + document.writeln( " HTML font size " + counter + " " ); counter + " " );</SCRIPT></HEAD><BODY></BODY></HTML>

42 JavaScript, by Dr. Khalil42

43 JavaScript, by Dr. Khalil43 Sentinel-controlled loop Class Average Program Class Average Program var total,// sum of grades gradeCounter,// number of grades entered gradeCounter,// number of grades entered gradeValue,// grade value gradeValue,// grade value average,// average of all grades average,// average of all grades grade;// grade typed by uesr grade;// grade typed by uesr // initialization phase total = 0;// clear total gradeCounter = 0;// initialize the counter // processing phase // prompt for input and read grade from user grade = window.prompt ( "Enter integer grade, -1 to Quit:", "0" ); gradeValue = parseInt( grade ); while ( gradeValue != -1 ) { total = total + gradeValue; total = total + gradeValue; gradeCounter = gradeCounter + 1; gradeCounter = gradeCounter + 1; grade = window.prompt ( "Enter integer grade, -1 to Quit:", "0" ); grade = window.prompt ( "Enter integer grade, -1 to Quit:", "0" ); gradeValue = parseInt( grade ); gradeValue = parseInt( grade );} if ( gradeCounter != 0 ) { average = total / gradeCounter; average = total / gradeCounter; document.writeln( " Class average is " + average + " " ); document.writeln( " Class average is " + average + " " );}else document.writeln( " No grades were entered!!" ); document.writeln( " No grades were entered!!" );</SCRIPT> Refresh to run the script again Refresh to run the script again </HTML>

44 JavaScript, by Dr. Khalil44

45 JavaScript, by Dr. Khalil45 Calculating Compound Interest with for loop Calculating Compound Interest Calculating Compound Interest var amount, principal = 1000, rate = 0.1; document.writeln( " " ); document.writeln( " Year " ); document.writeln( " Amount on deposit " ); for ( var year = 1; year <= 10; ++year ) { amount = principal * Math.pow(1.0 + rate, year); amount = principal * Math.pow(1.0 + rate, year); document.writeln( " " + year + " " + document.writeln( " " + year + " " + Math.round(amount * 100) / 100 + " " ); Math.round(amount * 100) / 100 + " " );} doccument.writeln( " " ); </SCRIPT></HEAD><BODY></BODY></HTML>

46 JavaScript, by Dr. Khalil46

47 JavaScript, by Dr. Khalil47

48 JavaScript, by Dr. Khalil48 Break and Continue var x = 1; while (x <= 20) { if (x == 7) continue; // skip the number 7 if (x == 7) continue; // skip the number 7 // statement(s) to execute if x does not equal 7 // statement(s) to execute if x does not equal 7 }--------------------------------------------------------------------------------------- var y = 1; while (y <= 20) { if (x == 100) break; // if x = 100, leave the loop if (x == 100) break; // if x = 100, leave the loop // statement(s) to execute // statement(s) to execute } // execution continues here when y > 20 or x = 100 // execution continues here when y > 20 or x = 100---------------------------------------------------------------------------------------

49 JavaScript, by Dr. Khalil49 Labels var x = 100; code_loop: while (x <= 1000) { // statement(s) // statement(s) }--------------------------------------------------------------------------------------- var x = 0, y = 0; top_loop: while (x <= 100) { while (y <= 50) { while (y <= 50) { …………… …………… if (z == 100) break top_loop; if (z == 100) break top_loop; } } // execution resumes here after loops are complete or if z = 100 during the loops execution ------------------------------------------------------------------------------------------------------------------------- - code_block: { // block of code here // block of code here }

50 JavaScript, by Dr. Khalil50 Functions  Experience has shown that the best way to develop and maintain a large program is to construct it from small, simple pieces or modules. This technique is called divide and conquer.  Modules in JavaScript are called functions. JavaScript programs are written by combining new functions that the programmer writes with “prepackaged” functions and objects available in JavaScript.  The “prepackaged” functions that belong to JavaScript objects are often called. The term method implies that the function belongs to a particular object.  The “prepackaged” functions that belong to JavaScript objects are often called methods. The term method implies that the function belongs to a particular object.  The programmer can write programmer-defined functions to define specific tasks that may be used at many points in a script. The actual statements defining the function are written only once, and these statements are hidden from other functions.  A is invoked by a function call. The function call specifies the function name and provides information (as arguments) that the called function needs to do its task.  A function is invoked by a function call. The function call specifies the function name and provides information (as arguments) that the called function needs to do its task.  Functions allow the programmer to modularize a program.  All variables declared in function definitions are local variables – they are known only in the function in which they are defined.  Most functions have parameters that provide the means for communicating information between functions via function calls. A function’s parameters are also considered to be local variables.  The divide-conquer approach to program development makes program development more manageable.

51 JavaScript, by Dr. Khalil51 Functions  The represent the function call operator  The () represent the function call operator  The statement passes the result of a function call back to the calling function.  The return statement passes the result of a function call back to the calling function.  The format of a function definition is function-name( parameter-list ) Function function-name( parameter-list ){ declarations and statements }

52 JavaScript, by Dr. Khalil52 Built-in Functions FunctionUseReturns escape Creates portable data – typically used to encode URLs and other information that may include extended characters (non-alphanumeric). Extended characters are replaced by their ASCII number equivalent in hexadecimal %xx form. For example, a space (ASCII 20) becomes %20. Encoded version of supplied argument eval Parse the supplied string for JavaScript code and executes the code if found The value of the last valid statement or expression encountered in the supplied argument. isFinite Tests an expression or variable to see if it is a valid number. True if the supplied argument is a Valid number, false otherwise. isNaN Tests an expression or variable to see if it is not a ((valid) number. Returns true if the argument is not a number and false otherwise. number Converts an object (typically string data) to a number. Returns the supplied argument converted to a number or the value NaN if the argument cannot be converted to a valid number. parseFloat Parses the given argument for a valid floating- point number. A floating-point representation of the supplied argument. parseInt Parses the given argument for a valid integer number. An integer representation of the supplied argument. string Converts the supplied argument to a string representation. A string representation of the supplied argument. Unescape Converts portable data back into its original form. Decoded version of the supplied argumemt.

53 JavaScript, by Dr. Khalil53 User-Defined Functions  JavaScript supports user-defined functions which allow users to better organize their code into discrete, reusable chunks. User-defined functions have the following syntax: function ( ) { … code of function … return ; }  For example: function spacefill(text) { while (text.length < 25) { text = text + “ “; } return text; } -----------------------------------------------------------------------------------  Elsewhere in your code, you can use this function: address = spacefill(address);

54 JavaScript, by Dr. Khalil54 Example – User-defined Functions A Programmer-Defined Square Function A Programmer-Defined Square Function document.writeln( " Square the numbers from 1 to 10 " ); // square the numbers from 1 to 10 for ( var x = 1; x <= 10; ++x ) document.writeln( "The square of " + x + " is " + square( x ) + " " ); // square function definition function square( y ) { return y * y; }</SCRIPT></HEAD><BODY></BODY></HTML>

55 JavaScript, by Dr. Khalil55

56 JavaScript, by Dr. Khalil56 A Programmer-Defined maximum Function A Programmer-Defined maximum Function var input1 = window.prompt( "Enter first number", "0" ); var input2 = window.prompt( "Enter second number", "0" ); var input3 = window.prompt( "Enter third number", "0" ); var value1 = parseInt( input1 ); var value2 = parseInt( input2 ); var value3 = parseInt( input3 ); var maxValue = maximum( value1, value2, value3 ); document.writeln( "First number: " + value1 + " Second number: " + value2 + " Third number: " + value3 + " Maximum is: " + maxValue ); // maximum function definition function maximum( x, y, z ) { return Math.max( x, Math.max( y, z ) ); }</SCRIPT></HEAD><BODY></BODY></HTML>

57 JavaScript, by Dr. Khalil57 Objects  are a natural way of thinking about the world.  Objects are a natural way of thinking about the world.  Objects encapsulate data (attributes) and methods (behavior).  Objects have the property of information hiding.  Programs communicate with objects by using well-defined interfaces.  World Wide Web browsers have a set of objects that encapsulate the elements of an HTML document and expose to a JavaScript programmer attributes and behaviors that enable a JavaScript program to interact with (or script) the elements (i.e., objects) in an HTML document.  object methods allow programmers to perform many common mathematical calculations.  Math object methods allow programmers to perform many common mathematical calculations.  An object’s methods are called by writing the name of the object followed by a dot (.) and the name of the method. In parentheses following the method name is the argument (or a comma-separated list of arguments) to the method.  object provides several methods enabling processing String objects.  String object provides several methods enabling processing String objects.

58 JavaScript, by Dr. Khalil58 Built-in Objects  JavaScript is an object-driven language. “The Document Object Model” – the user agent – supplies a host of objects that your scripts can reference.  JavaScript has several built-in objects. For example, two specific objects exist for manipulating data: one for performing math operations () on numeric data and another for performing operations on string values ().  JavaScript has several built-in objects. For example, two specific objects exist for manipulating data: one for performing math operations ( Math ) on numeric data and another for performing operations on string values ( String ).  These objects have various methods for acting upon data: x = Math.sqrt(x); // square root of x s = String.toLowerCase(s); // convert s to lowercase  JavaScript also supports the with statement: with (Math) { y = random(200); x = round (sqrt(y)); }  Another useful object is the object which has several methods that can be used to manipulate dates and times in various formats:  Another useful object is the Date object which has several methods that can be used to manipulate dates and times in various formats: months = new Array(“January”, “February”, “March”, “April”, “May”, “June”, “July”, “August”, “September”, “October”, “November”, “December”); var today = new Date(); var day = today.getDate(); var month = today.getMonth(); var year = today.getYear(); document.write(months[month]+” “+day+”, “+year);

59 JavaScript, by Dr. Khalil59 Methods  The object’s method determines the larger of its two statement values.  The Math object’s max method determines the larger of its two statement values.  The object’s method generates a real value from 0.0 up to (but not including) 1.0.  The Math object’s random method generates a real value from 0.0 up to (but not including) 1.0.  object’s rounds its real number argument to the closest integer not greater than its argument’s value.  Math object’s floor rounds its real number argument to the closest integer not greater than its argument’s value.  The values produced directly by random are always in the range: 0.0 <= Math.random() < 1.0  We can generalize picking a random number from a range of values by writing: value = Math.floor( a + Math.random() * b) ;  Where is the shifting value (the first number in the desired range of consecutive integers) and is the scaling factor (the width of the desired range of consecutive integers).  Where a is the shifting value (the first number in the desired range of consecutive integers) and b is the scaling factor (the width of the desired range of consecutive integers).

60 JavaScript, by Dr. Khalil60 Math Object’s Methods MethodDescriptionMethodDescription abs( x ) Absolute value of x round( x ) Rounds x to the closest integer ceil( x ) Rounds x to the smallest integer not less than x sin( x ) Trigonometric sine of x (x in radians) cos( x ) Trigonometric cosine of x (x in radians) sqrt( x ) Square root of x exp( x ) Exponential method e x tan( x ) Trigonometric tangent of x (x in radians) floor( x ) Rounds x to the largest integer not greater than x log( x ) Natural logarithm of x (base e) max( x, y ) Larger value of x and y min( x, y ) Smaller value of x and y pow( x, y ) X raised to power y (x y )

61 JavaScript, by Dr. Khalil61 Random Number Generation Shifted and Scaled Random Integers Shifted and Scaled Random Integers var value; document.writeln( " Random Numbers " + " " ); for ( var i = 1; i <= 20; i++ ) { value = Math.floor( 1 + Math.random() * 6 ); document.writeln( " " + value + " " ); if ( i % 5 == 0 && i != 20 ) document.writeln( " " ); } </SCRIPT></HEAD><BODY></BODY></HTML>

62 JavaScript, by Dr. Khalil62

63 JavaScript, by Dr. Khalil63 User-Created Objects  The new declaration statement can be used to create new objects based on existing, built- in objects, for example: employees = new Array(“Khalil”, “Sameh”, “Sherif”, “Amr”, “Khaled”);  JavaScript also includes built-in constructors for native objects: function movie (title, genre, releasedate) { this.title = title; this.genre = genre; this.releasedate = releasedate; }  The constructor can be called as follows: mov1 = new movie(“Aliens”, Scifi”, “1986-07-18”);  The same object can be created without use of constructor as follows: mov1 = new object(); move1.title = “Aliens”; move1.genre = “Scifi”; move1.releasedate = “1986-07-18”;

64 JavaScript, by Dr. Khalil64 Arrays  are data structures consisting of related data items.  Arrays are data structures consisting of related data items.  An array is a group of memory locations that all have the same name and are normally of the same type.  To refer to a particular location or element in the array, specify the name of the array and the position number () of the particular element in the array.  To refer to a particular location or element in the array, specify the name of the array and the position number ( index ) of the particular element in the array.  The index (or ) must be an integer or an integer expression and the first element in every array is of index.  The index (or subscript ) must be an integer or an integer expression and the first element in every array is of index 0.  The length (size) of an array is the number of its elements and is determined by arrayName..  The length (size) of an array is the number of its elements and is determined by arrayName. length.  An array in JavaScript is an object. Operator is used to dynamically allocate the number of elements required by an array. Operator creates an object as the program executes, by obtaining enough memory to store an object of the type specified to the right of.  An array in JavaScript is an Array object. Operator new is used to dynamically allocate the number of elements required by an array. Operator new creates an object as the program executes, by obtaining enough memory to store an object of the type specified to the right of new.  The process of creating new objects is also known as creating an instance or instantiating an object.  An array can be initialized with a comma-separated initializerl ist enclosed in square brackets [ ].  JavaScript’s for/in control structure enables a script to perform a task for each element in an array: ( var element in arrayName ) for ( var element in arrayName )statement

65 JavaScript, by Dr. Khalil65 Arrays – An Example I Initializing an Array Initializing an Array // this function is called when the element's // ONLOAD event occurs. function initializeArrays() { var n1 = new Array( 5 );// allocate 5-element Array var n2 = new Array();// allocate empty Array // assign values to each element of Array n1 for ( var i = 0; i < n1.length; ++i ) n1[i] = i * i; // create and initialize 6 elements in Array n2 for ( i = 0; i < 6; ++i ) n2[i] = 2 * i; outputArray( "Array n1 contains", n1 ); outputArray( "Array n2 contains", n2 ); } // output "header" followed by a two-column table // containing subscripts and elements of "theArray" function outputArray( header, theArray ) { document.writeln( " " + header + " " ); document.writeln( " " ); document.writeln( " Subscript “ + " Value " ); for ( var i = 0; i < theArray.length; i++ ) document.writeln( " " + i + " " + theArray[i] + " " ); document.writeln( " " ); }</SCRIPT></HEAD> </BODY></HTML>

66 JavaScript, by Dr. Khalil66

67 JavaScript, by Dr. Khalil67 Arrays – An Example II Student Poll Program Student Poll Program function start() { var responses = [ 1, 2, 6, 4, 8, 5, 9, 7, 8, 10, 1, 6, 3, 8, 6, 10, 3, 8, 2, 7, 6, 5, 7, 6, 8, 6, 7, 5, 6, 6, 5, 6, 7, 5, 6, 4, 8, 6, 8, 10 ]; 5, 6, 7, 5, 6, 4, 8, 6, 8, 10 ]; var frequency = [, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]; for ( var answer in responses ) ++frequency[ responses[ answer ] ]; document.writeln( " " ); document.writeln( " Rating " + " Frequency " ); for ( var rating = 1; rating < frequency.length; ++rating ) document.writeln( " " + rating + " " + frequency[rating] + " " ); document.writeln( " " ); }</SCRIPT></HEAD> </BODY></HTML>

68 JavaScript, by Dr. Khalil68

69 JavaScript, by Dr. Khalil69 Event Handling  One of the more powerful anf often used techniques concerning JavaScript is events. Using event attributes in XHTML tags, such as onmouseover and onclick, you can create interactive documents that respond to user’s actions. EventTrigger onAbort Abort selected in browser (stop loading of image or document), usually by clicking the Stop button onBlur When the object loses focus onChange When an object is changed (generally a form element) onClick When the object is clicked onDblClick When the object is double-clicked onDragDrop When a object is dropped into the user agent window onError When a JavaScript error occurs onFocus When an object receives focus onKeyDown When the user presses a key onKeyPress When the user presses and/or holds down a key onKeyUp When the user releases a key Onload When the object is loaded into the user agent window (typically used with the element to run a script when the document has completed loading)

70 JavaScript, by Dr. Khalil70 Event Handling (Cont’d)EventTrigger onMouseDown When the mouse butoon is depressed onMouseMove When the mouse is moved onMouseOut When the mouse pointer moves outside the boundary of an object onMouseOver When the mouse pointer moves within the boundary of an object onMouseUp When the mouse button is released onMove When an object (generally a window or frame) is moved onReset When the user selects a reset button onResize When an object (generally a window or frame) is resized onSelect When the user selects text within the object (generally a form element) onSubmit When the user selects a submit button OnUnload When the object is unloaded from the user agent window (typically used with the element to run a script when the user navigates away from a document – a favorite tool of pop-up window coders)

71 JavaScript, by Dr. Khalil71 Key Points  The language facilitates a disciplined approach to designing computer programs that enhance Web pages.  The JavaScript language facilitates a disciplined approach to designing computer programs that enhance Web pages.  Often JavaScripts appear in the section of the HTML document.  The browser interprets the contents of the section first.  The tag indicates to the browser that the text that follows is part of a script. Attribute specifies the scripting language used in the script – such as  The tag indicates to the browser that the text that follows is part of a script. Attribute LANGUAGE specifies the scripting language used in the script – such as JavaScript.  Every statement should end with a semicolon.  JavaScript is case sensitive.  A string of characters can be contained between the double quotation (“) marks or single quotation (‘) marks.  A string is sometimes called a character string, a message or string literal.  The browser’s object represents the HTML document currently being displayed in the browser. The document object allows a script programmers to specify HTML text to be displayed in the HTML document.  The browser’s document object represents the HTML document currently being displayed in the browser. The document object allows a script programmers to specify HTML text to be displayed in the HTML document.  The browser contains a complete set of objects that allow script programmers every element of an HTML document.  An object resides in the computer’s memory and contains information used by the script. The term object normally implies that attributes (data) and behaviors (methods) are associated with the object. The object’s methods use the attributes to provide useful services to the client of the object – the script that calls the methods.

72 JavaScript, by Dr. Khalil72 Key Points  The object’s method writes a line of HTML text in the HTML document.  The document object’s writeln method writes a line of HTML text in the HTML document.  Unlike, method does not position the output cursor in the HTML document at the beginning of next line of HTML text after writing its argument.  Unlike writeln, document method write does not position the output cursor in the HTML document at the beginning of next line of HTML text after writing its argument.  Each and statement resumes writing characters where the last write or writeln stopped writing characters.  Each write and writeln statement resumes writing characters where the last write or writeln stopped writing characters.  Sometimes it is useful to display information in windows called dialog boxes that “pop up” on the screen to grab the user’s attention. Dialog boxes are typically used to display important messages to the user who is browsing the Web page. The browser’s object displays an alert dialog box with method. Method requires as its argument the string to display.  Sometimes it is useful to display information in windows called dialog boxes that “pop up” on the screen to grab the user’s attention. Dialog boxes are typically used to display important messages to the user who is browsing the Web page. The browser’s window object displays an alert dialog box with method alert. Method alert requires as its argument the string to display.  Normally the characters in a string are displayed exactly as they appear between the double quotes. When a backslash is encountered in a string of characters, the next character is combined with the backslash to form an escape sequence. The escape sequence is the newline character. It causes the cursor in the HTML document to move to the beginning of the next line in the dialog box.  Normally the characters in a string are displayed exactly as they appear between the double quotes. When a backslash is encountered in a string of characters, the next character is combined with the backslash to form an escape sequence. The escape sequence \n is the newline character. It causes the cursor in the HTML document to move to the beginning of the next line in the dialog box.

73 JavaScript, by Dr. Khalil73 Key Points  The keyword is used to declare the names of variables. A variable is a location in the computer’s memory where a value can be stored for use by a program. Though not required, all variables should be declared with a name in a statement before they are used in a program.  The keyword var is used to declare the names of variables. A variable is a location in the computer’s memory where a value can be stored for use by a program. Though not required, all variables should be declared with a name in a var statement before they are used in a program.  A variable name can be any valid identifier. An identifier is a series of characters consisting of letters, digits, underscores (_) and dollar signs ($) that does not contain any spaces.  Programmers often indicate the purpose of each variable in the program by placing a JavaScript comment at the end of each line in the declaration. A single-line comment begins with the characters and terminate at the end of the line. Comments do not cause the browser to perform any action when the script is interpreted; rather, comments are ignored by the JavaScript interpreter.  Programmers often indicate the purpose of each variable in the program by placing a JavaScript comment at the end of each line in the declaration. A single-line comment begins with the characters // and terminate at the end of the line. Comments do not cause the browser to perform any action when the script is interpreted; rather, comments are ignored by the JavaScript interpreter.  Multiple-line comments begin with delimiter and end with delimiter. All text between the delimiters of the comment is ignored by the JavaScript interpreter.  Multiple-line comments begin with delimiter /* and end with delimiter */. All text between the delimiters of the comment is ignored by the JavaScript interpreter.  The object’s method displays a dialog into which the user can type a value. The first argument is a message (called a prompt) that directs the user to take a specific action. The optional second argument is the default string to display in the text field.  The window object’s prompt method displays a dialog into which the user can type a value. The first argument is a message (called a prompt) that directs the user to take a specific action. The optional second argument is the default string to display in the text field.

74 JavaScript, by Dr. Khalil74 Key Points  A variable is assigned a value with an assignment statement using the assignment operator. The operator is called a binary operator because it has two operands.  A variable is assigned a value with an assignment statement using the assignment operator =. The = operator is called a binary operator because it has two operands.  Function converts its string argument to an integer.  Function parseInt converts its string argument to an integer.  JavaScript has a version of the operator for string concatenation that enables a string and a value of another data type (including another string) to be concatenated.  JavaScript has a version of the + operator for string concatenation that enables a string and a value of another data type (including another string) to be concatenated.  When a value is placed in a memory location, this value replaces the previous value in that location.  Operators in arithmetic expressions are applied in a precise sequence determined by the rules of operator precedence.  Parentheses may be used to force the order of evaluation of operators to occur in any sequence desired by the programmer.  Java’s structure allows a program to make a decision based on the truth or falsity of a condition. If the condition is met (the condition is true), the statement in the body of thestructure is executed. If the condition is not met (the condition is false), the body statement is not executed.  Java’s if structure allows a program to make a decision based on the truth or falsity of a condition. If the condition is met (the condition is true), the statement in the body of the if structure is executed. If the condition is not met (the condition is false), the body statement is not executed.  Conditions in structures can be formed by using the equality and relational operators.  Conditions in if structures can be formed by using the equality and relational operators.

75 JavaScript, by Dr. Khalil75 Thank you


Download ppt "JavaScript, by Dr. Khalil1 JavaScript Dr. Awad Khalil Computer Science Department AUC."

Similar presentations


Ads by Google