1 / 57

JavaScript by Dr. Khalil - Introduction to Basic Concepts and Programming

Learn JavaScript programming through Dr. Khalil's comprehensive guide. Explore basic concepts, control structures, loops, functions, and more.

wallerr
Download Presentation

JavaScript by Dr. Khalil - Introduction to Basic Concepts and Programming

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


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

  2. Content • Introduction • Basic Concepts • Making Selections – Control Structures • Making Repetitions (Loops) • Logical Operations • Functions - Methods • Objects JavaScript, by Dr. Khalil

  3. Introduction • 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, while Microsoft’s version of JavaScript is called Jscript. JavaScript, by Dr. Khalil

  4. <HTML> <HEAD> <TITLE>A First Program in JavaScript</TITLE> <SCRIPT LANGUAGE=“JavaScript”> document.writeln(“<H1>Welcome to JavaScript Programming!</H1>”); </SCRIPT> </HEAD><BODY></BODY> </HTML> Simple Examples – First Program in JavaScript JavaScript, by Dr. Khalil

  5. Example 2 – Printing on one line <HTML> <HEAD> <TITLE>A First Program in JavaScript</TITLE> <SCRIPT> document.write( “<FONT COLOR=‘red’><H1>Welcome to “ document.writeln(“JavaScript Programming!</H1></FONT>”); </SCRIPT> </HEAD><BODY></BODY> </HTML> JavaScript, by Dr. Khalil

  6. Example 3 – Printing on multiple lines <HTML> <HEAD> <TITLE>Printing Multiple Lines</TITLE> <SCRIPT LANGUAGE=“JavaScript”> document.writeln(“<H1>Welcome to <BR>JavaScript<BR> Programming!</H1>”); </SCRIPT> </HEAD><BODY></BODY> </HTML> JavaScript, by Dr. Khalil

  7. Example 4 – Displaying multiple lines in a dialog box <HTML> <HEAD> <TITLE>Printing Multiple Lines</TITLE> <SCRIPT LANGUAGE=“JavaScript”> window.alert(“Welcome to\nJavaScript\nProgramming!”); </SCRIPT> </HEAD><BODY></BODY> </HTML> JavaScript, by Dr. Khalil

  8. Example 5 – Adding Integers <HTML> <HEAD> <TITLE>An Addition Program</TITLE> <SCRIPT LANGUAGE=“JavaScript”> 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( “<H1>The sum is “ + sum + “</H1>”); </SCRIPT> </HEAD><BODY></BODY> </HTML> JavaScript, by Dr. Khalil

  9. Example 5 – Adding Integers JavaScript, by Dr. Khalil

  10. Arithmetic Operators JavaScript, by Dr. Khalil

  11. Decision Making – Relational Operators JavaScript, by Dr. Khalil

  12. Decision Making – An Example <HTML> <HEAD> <TITLE>Performing Comparisons</TITLE> <SCRIPT LANGUAGE=“JavaScript”> 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( “<H1>Comparison Results</H1>” ); document.writeln( “<TABLE BORDER = ‘1’ WIDTH = ‘100%’>” ); if ( first == second ) document.writeln( “<TR><TD>” + first + “ == “ + second + “</TD></TR>” ); if ( first != second ) document.writeln( “<TR><TD>” + first + “ != “ + second + “</TD></TR>” ); if ( first > second ) document.writeln( “<TR><TD>” + first + “ > “ + second + “</TD></TR>” ); if ( first >= second ) document.writeln( “<TR><TD>” + first + “ >= “ + second + “</TD></TR>” ); if ( first < second ) document.writeln( “<TR><TD>” + first + “ < “ + second + “</TD></TR>” ); if ( first <= second ) document.writeln( “<TR><TD>” + first + “ >= “ + second + “</TD></TR>” ); document.writeln( “</TABLE>” ); </SCRIPT> </HEAD><BODY></BODY> </HTML> JavaScript, by Dr. Khalil

  13. JavaScript, by Dr. Khalil

  14. JavaScript, by Dr. Khalil

  15. Key Points • The JavaScript language facilitates a disciplined approach to designing computer programs that enhance Web pages. • Often JavaScripts appear in the <HEAD> section of the HTML document. • The browser interprets the contents of the <HEAD> section first. • The <SCRIPT> 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 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. JavaScript, by Dr. Khalil

  16. Key Points • The document object’s writeln method writes a line of HTML text in the HTML document. • 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 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 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\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. JavaScript, by Dr. Khalil

  17. Key Points • 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. • 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 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. JavaScript, by Dr. Khalil

  18. 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. • 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. • 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 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 if structures can be formed by using the equality and relational operators. JavaScript, by Dr. Khalil

  19. 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<BR>” ); document.writeln ( “You must repeat this course” ); } Control Structures JavaScript, by Dr. Khalil

  20. 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” ); Control Structures JavaScript, by Dr. Khalil

  21. switch structure switch ( gradeLetter ) { case “A”: gradeName = “Excellent; break; case “B”: gradeName = “Very Good”; break; case “C”: gradeName = “Good”; break; case “D”: gradeName = “Sufficient”; break; case “F”: gradeName = “Fail”; break; default: gradeName = “Invalid grade”; } Control Structures JavaScript, by Dr. Khalil

  22. while var product = 2; while ( product <= 100 ) product = product * 2; ----------------------------------------------------------------------------------------------- var counter = 1 while ( counter <= 30 ) { sum = sum + score; counter = counter + 1; } ----------------------------------------------------------------------------------------------- Repetition Structures (Loops) JavaScript, by Dr. Khalil

  23. Counter-controlled loop – An Example <HTML><HEAD><TITLE>Class Average Program</TITLE> <SCRIPT LANGUAGE="JavaScript"> var total, // sum of grades gradeCounter, // number of grades entered gradeValue, // grade value average, // average of all grades 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" ); gradeValue = parseInt( grade ); total = total + gradeValue; gradeCounter = gradeCounter + 1; } average = total / 10; document.writeln( "<H1>Class average is " + average + "</H1>" ); </SCRIPT> </HEAD><BODY>Refresh to run the script again</BODY> </HTML> JavaScript, by Dr. Khalil

  24. JavaScript, by Dr. Khalil

  25. Sentinel-controlled loop <HTML><HEAD><TITLE>Class Average Program</TITLE> <SCRIPT LANGUAGE="JavaScript"> var total, // sum of grades gradeCounter, // number of grades entered gradeValue, // grade value average, // average of all grades 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; gradeCounter = gradeCounter + 1; grade = window.prompt ( "Enter integer grade, -1 to Quit:", "0" ); gradeValue = parseInt( grade ); } if ( gradeCounter != 0 ) { average = total / gradeCounter; document.writeln( "<H1>Class average is " + average + "</H1>" ); } else document.writeln( "<p>No grades were entered!!" ); </SCRIPT> </HEAD><BODY>Refresh to run the script again</BODY> </HTML> JavaScript, by Dr. Khalil

  26. JavaScript, by Dr. Khalil

  27. Increment and Decrement Operators JavaScript, by Dr. Khalil

  28. Increment and Decrement Operators JavaScript, by Dr. Khalil

  29. Counter-controlled while loop - An Example General Format: initialization; while ( loopContinuationTest ) { statement increment; } ---------------------------------------------------------------------------------------------------------------- <HTML> <HEAD> <TITLE>Counter-controlled loops</TITLE> <SCRIPT LANGUAGE="JavaScript"> var counter = 1; // initialize the counter while ( counter <= 7 ) // loop condition { document.writeln( "<p><FONT SIZE = '" + counter + "'>HTML font size " + counter + "</FONT></p>" ); ++counter; // increment } </SCRIPT> </HEAD><BODY></BODY> </HTML> JavaScript, by Dr. Khalil

  30. JavaScript, by Dr. Khalil

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

  32. JavaScript, by Dr. Khalil

  33. Calculating Compound Interest with for loop <HTML><HEAD><TITLE>Calculating Compound Interest</TITLE> <SCRIPT LANGUAGE="JavaScript"> var amount, principal = 1000, rate = 0.1; document.writeln( "<TABLE BORDER='100' WIDTH='100%'>" ); document.writeln( "<TR><TD WIDTH= '100'><B>Year</B></TD>" ); document.writeln( "<TD><B>Amount on deposit</B></TD></TR>" ); for ( var year = 1; year <= 10; ++year ) { amount = principal * Math.pow(1.0 + rate, year); document.writeln( "<TR><TD>" + year + "</TD><TD>" + Math.round(amount * 100) / 100 + "<TD></TR>" ); } doccument.writeln( "</TABLE>" ); </SCRIPT> </HEAD><BODY></BODY> </HTML> JavaScript, by Dr. Khalil

  34. JavaScript, by Dr. Khalil

  35. The do/while loop General Format: do { statement } while ( condition ); ----------------------------------------------------------------------------------------------------- <HTML> <HEAD> <TITLE>Using the do/while loop</TITLE> <SCRIPT LANGUAGE="JavaScript"> var counter = 1; do { document.writeln( "<H" + counter + ">This is an H" + counter + " level head" + "</H" + counter + ">" ); ++ counter; } while ( counter <= 6 ); </SCRIPT> </HEAD><BODY></BODY> </HTML> JavaScript, by Dr. Khalil

  36. JavaScript, by Dr. Khalil

  37. The Logical Operators JavaScript, by Dr. Khalil

  38. Demonstrating the Logical Operators <HTML><HEAD><TITLE>Demonstrating the logical operators</TITLE> <SCRIPT LANGUAGE="JavaScript"> document.writeln( "<TABLE BORDER='10' WIDTH='100%'>" ); document.writeln( "<TR><TD WIDTH= '25%'>Logical AND (&&)</TD>" + "<TD>false && false: " + ( false && false ) + "<BR>false && true: " + ( false && true ) + "<BR>true && false: " + ( true && false ) + "<BR>true && true: " + ( true && true ) + "</TD>" ); document.writeln( "<TR><TD WIDTH= '25%'>Logical OR (||)</TD>" + "<TD>false || false: " + ( false || false ) + "<BR>false || true: " + ( false || true ) + "<BR>true || false: " + ( true || false ) + "<BR>true || true: " + ( true || true ) + "</TD>" ); document.writeln( "<TR><TD WIDTH= '25%'>Logical NOT (!)</TD>" + "<TD>!false: " + ( !false ) + "<BR>!true: " + ( !true ) + "</TD>" ); doccument.writeln( "</TABLE>" ); </SCRIPT> </HEAD><BODY></BODY> </HTML> JavaScript, by Dr. Khalil

  39. JavaScript, by Dr. Khalil

  40. 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 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 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. JavaScript, by Dr. Khalil

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

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

  43. JavaScript, by Dr. Khalil

  44. Methods • The Math object’s max method determines the larger of its two statement values. • The Math object’s random method generates a real value from 0.0 up to (but not including) 1.0. • 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 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). JavaScript, by Dr. Khalil

  45. <HTML><HEAD><TITLE>A Programmer-Defined maximum Function</TITLE> <SCRIPT LANGUAGE="JavaScript"> 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 + "<BR>Second number: " + value2 + "<BR>Third number: " + value3 + "<BR> Maximum is: " + maxValue ); // maximum function definition function maximum( x, y, z ) { return Math.max( x, Math.max( y, z ) ); } </SCRIPT> </HEAD><BODY></BODY> </HTML> JavaScript, by Dr. Khalil

  46. Random Number Generation <HTML><HEAD><TITLE>Shifted and Scaled Random Integers</TITLE> <SCRIPT LANGUAGE="JavaScript"> var value; document.writeln( "<H1>Random Numbers</H1>" + "<TABLE BORDER = '5' WIDTH = '50%'><TR>" ); for ( var i = 1; i <= 20; i++ ) { value = Math.floor( 1 + Math.random() * 6 ); document.writeln( "<TD>" + value + "</TD>" ); if ( i % 5 == 0 && i != 20 ) document.writeln( "</TR><TR>" ); } document.writeln( "</TR></TABLE>" ); </SCRIPT> </HEAD><BODY></BODY></HTML> JavaScript, by Dr. Khalil

  47. JavaScript, by Dr. Khalil

  48. Key Points • Any computing problem can be solved by executing a series of actions in specific order. • A procedure for solving a problem in terms of the actions to be executed and the order in which these actions are to be executed is called an algorithm. • Specifying the order in which statements are to be executed in a computer program is called program control. • Normally, statements in a program are executed one after the other, in the order they are written. This is called sequential execution. • Various JavaScript statements enable the programmer to specify that the next statement to be executed may be other than the next one in sequence. This is called transfer of control. • All programs can be written in terms of only three control structures, namely by the sequence structure, the selection structure and the repetition structure. • JavaScript provides three types of selection structures. The if selection structure either performs (selects) an action if a condition is true or skips the action if the condition is false. The if/else selection structure performs an action if a condition is true and performs a different action if the condition is false. The switch selection structure performs one of many different actions, depending on the value of an expression. • JavaScript provides four types of repetition structures, namely while, do/while, for, and for/in. JavaScript, by Dr. Khalil

  49. Arrays • 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 (index) of the particular element in the array. • 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.length. • 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: for ( var element in arrayName ) statement JavaScript, by Dr. Khalil

  50. Arrays – An Example I <HTML><HEAD><TITLE>Initializing an Array</TITLE> <SCRIPT LANGUAGE="JavaScript"> // this function is called when the <BODY> 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( "<H2>" + header + "</H2>" ); document.writeln( "<TABLE BORDER='10' WIDTH='100%'>" ); document.writeln( "<TR><TD WIDTH='100'><B>Subscript</B>“ + "<TD><B>Value</B></TR>" ); for ( var i = 0; i < theArray.length; i++ ) document.writeln( "<TR><TD>" + i + "<TD>" + theArray[i] + "</TR>" ); document.writeln( "</TABLE>" ); } </SCRIPT> </HEAD> <BODY ONLOAD = "initializeArrays()"> </BODY> </HTML> JavaScript, by Dr. Khalil

More Related