1 / 152

JavaScript

JavaScript. IT Engineering I Instructor: Behrang Assemi. Why JavaScript?. HTML ‘s role on the Web Purpose  tell the browser how a document should appear Static  fixed view (no interaction) JavaScript ‘s role on the Web Purpose  make web pages more dynamic and interactive

venak
Download Presentation

JavaScript

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 IT Engineering I Instructor: Behrang Assemi

  2. Why JavaScript? • HTML‘s role on the Web • Purpose tell the browser how a document should appear • Staticfixedview (no interaction) • JavaScript‘s role on the Web • Purpose make web pages more dynamic and interactive • Change contents of document, provide forms and controls, animation, control web browser window, etc.

  3. Interaction So Scripting is needed Online calculator

  4. Dynamic Form Validation

  5. Registration form What is needed?

  6. Overview • Originally called LiveScript when introduced in Netscape Navigator • In Navigator 2.0, name changed to JavaScript • Current version 1.5 • JScript • MS version of JavaScript • Current version 5.5 • Two formats: • Client-side • Program runs on the client (browser) • Server-side • Program runs on the server • Proprietary to web server platform

  7. Overview (cont.) • A "scripting" language forHTML pages • Embed code in HTML • The browser interprets and executes the script • Not compiled • NO data types for variables • For security – cannot write to client’s disk

  8. JavaScript's abilities • Generating HTML content dynamically • Customize pages to suit users • Monitoring and responding to user events • Validate forms before submission • Interact with the frames and windows of the browser • manipulate "browser objects": • HTML form elements, Images, Frames, etc. • Manipulate HTTP cookies (to be discussed later)

  9. JavaScript is not Java • Java : • compilation required (not a scripting language) • can create "stand alone" application • Why it is called JavaScript then? • purely a marketing trick • JavaScript was originally called LiveScript • changed to JavaScript at the last minute

  10. Your Computer You Java Source Code Java Compiler (Mac) Java Compiler (PC) Java Compiler (Unix) Java Byte Code Byte Code Placed on the Web Server for Download Web Server Java Byte Code Java Interpreter (Mac) Java Interpreter (Unix) Java Interpreter (PC) Client Using Web Browser Java (Platform independent)

  11. Web Architecture for JavaScript "CLIENT" "SERVER" Desktop access Remotehost Web browser Web (HTTP) Server HTML Page: <SCRIPT> …code..… </SCRIPT> Internet HTML/HTTP TCP/IP HTML/HTTP TCP/IP built-in JavaScript interpreter HTML pages w/ embedded script

  12. JavaScript Versions • JavaScript 1.0 • The original version of the language. • It was buggy and is now essentially obsolete. • Implemented by Netscape 2. • JavaScript 1.1 • Introduced a true Array object; • most serious bugs resolved. • Implemented by Netscape 3. • JavaScript 1.2 • Introduced the switch statement, regular expressions, and a number of other features. • Almost compliant with ECMA v1, but has some incompatibilities. • Implemented by Netscape 4. • JavaScript 1.3 • Fixed incompatibilities of JavaScript 1.2. Compliant with ECMA v1. • Implemented by Netscape 4.5. • JavaScript 1.4 • Implemented only in Netscape server products. • JavaScript 1.5 • Introduced exception handling. Compliant with ECMA v3. Implemented by Mozilla and Netscape 6.

  13. Where Should I Write Javascript • JavaScript programs are written within an HTML document • Using the <script> Tag • <script>JavaScript Code</script> • Used to notify the browser that JavaScript statements are contained within the page

  14. The First JavaScript Program… • <script language="***"> • languageattribute • Denotes the scripting language being used • Default JavaScript • Other languages e.g. VBScript can be used • Also can specify the scripting language version • No space between name and version • Checked by browser, scripts ignored if browser doesn’t support the mentioned version

  15. The First JavaScript Program… • Object-based language • Object • Programming code and data that can be treated as an individual unit or component • Statements • Individual lines in a programming language • Methods • Groups of statements related to a particular object

  16. This is the windowobject This is the documentobject The First JavaScript Program • document object • Represents the content of a browser’s window • write() & writeln() • methods of Document object • Creates new text on the web page document.write("a new text");

  17. JavaScript: Hello world

  18. Write the JavaScript code for this page

  19. Comments in JavaScript • Two types • Line comments • //ignores all texts to the end of the line • Block comments • /*ignores all texts between these symbols */

  20. Comments in JavaScript (example)

  21. Remember HTML comments

  22. Hiding JavaScript from Incompatible Browsers What happens if JavaScript is turned off in a browser? • Twomethods • Place JavaScript in an external source file • Enclose the code within HTML comments <script language="JavaScript"> <!-– script statements go here //--> </script> • The start of the HTML comment (<!--) is straightforward. • But because the end-comment tag (-->) causes a syntax error in scriptable browsers: a JavaScript comment symbol (//) must precede the end-comment tag.

  23. When There Is No JavaScript • How to specify content that should appear only if JavaScript wasn’t available • Use <noscript> & </noscript> • to place alternate message to users of old browsers OR users with disabled javascript

  24. When There Is No JavaScript (example) //STOP HIDING FROM INCOMPATIBLE BROWSERS--> Only shown in browsers with disabled JavaScript

  25. JavaScript keywords

  26. JavaScript keywords (cont.)

  27. Variables Syntax rules • Cannot use: • Reserved words (keywords) & spaces • Must begin with one of the following characters: • Uppercase or lowercaseASCII letter (a-z, A-Z) • Dollar sign ($) or underscore (_) • Can use numbers, but not as the first character • Variables are case-sensitive

  28. Variables Conventions • Use underscore or capitalization to separate the different words of an identifier • employee_first_name • employeeFirstName • My_variable • $my_variable • _my_variable

  29. Illegal variable names

  30. Working with Variables • There are 3 ways To define a variable and assign a value to it: • Using the keyword var to declarea variable • Using the assignment operator to assign the variable a value varemployeeName; employeeName = "Ali"; varemployeeName = "Ali"; employeeName = "Hassan"; • Once created: May be changed at any point in the program • Values stored in memory • Values can vary over the time 1 2 3

  31. Wrappers and conversions • JavaScript has "wrapper" objects for when a primitive value must be treated as an object • var s = new String("Hello");// s is now a String • var n = new Number(5); // n is now a Number • var b = new Boolean(true);// b is now a Boolean • Because JavaScript does automatic conversions while needed, wrapper objects are hardly ever needed • JavaScript has no "casts“, but conversions can be forced • var s = x + "";// s is now a string • var n = x + 0;// n is now a number • var b = !!x;// b is now a boolean • Because JavaScript does automatic conversions while needed, explicit conversions are hardly ever needed

  32. Variable Scope • Defines where in the program a declared variable can be used • Global variable • Any variable definedoutside of a function is part of the global variable scope. • var keyword is optional • Local variable • Declared inside a function and is only available within the function it is declared. • Global and local variables can use the same identifiers

  33. Operators (I) • Arithmetic operators (all numbers are floating-point): + - * / % ++ -- • Comparison operators: < <= == != >= > • Logical operators: && || ! (&& and || are short-circuit operators) • Bitwise operators: & | ^ ~ << >> >>> • Assignment operators: += -= *= /= %= <<= >>= >>>= &= ^= |=

  34. Operators (II) • String operator: + varlongString = "One piece "+"plus one more piece."; • The conditional operator:condition ? value_if_true : value_if_false • (a>70)? state="old": state="young"; If (age>70){ state="old"; } else { state="young"; }

  35. Equality Operator == varstringA = "I am "; varstringB = new String("an intelligent person"); • Different Type! • The first variable is a string value, • The second variable is an instance of a String object. • If you place these two values on either side of an equality (==) operator, JavaScript tries various evaluations of the values to see if there is a coincidence somewhere. • Anyway stringA== stringB returns false. • ==and !=If the types of the two expressions are different, attempt to convert them to String, Number, or Boolean.

  36. Strict Equality Operator === • The strict equality operator (===), performs no data type conversions. • The types must be the same to be considered equal. • The following expression evaluates to false because the two object types differ, even though their payloads are the same: varstringA = "I am "; varstringB = new String("an intelligent person"); • stringA === stringBreturns false.

  37. boolean • The boolean values are true and false • When converted to a boolean, the following values are also false: • 0 • "0" and '0' • The empty string, '' or "" • undefined • null • NaN

  38. undefinedand null • There are special values undefined and null • undefinedis the only value of its "type" • This is the value of a variable that has been declared but not defined, or an object property that does not exist • void is an operator that, applied to any value, returns the value undefined • nullis an "object" with no properties • nulland undefined are == but not ===

  39. Numbers • In JavaScript, all numbers are floating point • Special predefined numbers: • Infinity, Number.POSITIVE_INFINITY -- the result of dividing a positive number by zero • Number.NEGATIVE_INFINITY -- the result of dividing a negative number by zero • NaN,Number.NaN (Not a Number) -- the result of dividing 0/0 • NaN is unequal to everything, even itself • There is a global isNaN() function • Number.MAX_VALUE -- the largest representable number • Number.MIN_VALUE -- the smallest (closest to zero) representable number

  40. Objects • An object is a collection of named values, • properties of the object. • fields of the object • if an object named image has properties named width and height, we can refer to those properties like this: • image.width • image.height • AndObjectMethods • document.write("this is a test");

  41. Object literals or object initializers • Object Literals • Allows you to create an object and specify its properties • Consists of a comma-separated list of colon-separated property/value pairs, all enclosed within curly braces. : • { name1 : value1 , ... , nameN : valueN } car={myCar:"Samand",getCar:CarTypes("Honda"),special:Sales} • The fields are myCar, getCar, and special • "Samand“ is a String • CarTypesis a function call with parameter Honda • Sales is a variable you defined earlier • Example: document.write("I own a " +car.myCar);

  42. Three waysto create an object • You can use an object literal: var course = { number: "IT402", teacher: "Mr. xyz" } • You can use new to create a "blank" object, and add fields to it later: var course = new Object(); course.number = "IT402"; course.teacher = "Mr. xyz"; • You can write and use a constructor: function Course(n, t) {// best placed in <head>this.number = n;// keyword "this" is required, not optionalthis.teacher = t; } var course = new Course("IT402", "Mr. xyz");

  43. Array literals color = ["red", "yellow", "green", "blue"]; • Arrays are zero-based:color[0]is"red" • two commas in a row: "empty" element in that location • Example:color = ["red", , , "green", "blue"]; • colorhas 5elements, two of them are empty • However, a single comma at the end is ignored • Example: color=["red", , , "green","blue",]; • still has 5 elements

  44. Four ways to create an array • You can use an array literal:var colors = ["red", "green", "blue"]; • You can use new Array()to create an empty array: • var colors = new Array(); • You can add elements to the array later:colors[0] = "red"; colors[2] = "blue"; colors[1] = "green"; • You can usenew Array(n)with a single numeric argument to create an array of that size • var colors = new Array(3); • You can usenew Array(…)with two or more arguments to create an array containing those values: • var colors = new Array("red", "green", "blue");

  45. The length of an array • IfmyArray is an array, its length is given by myArray.length • Array length can be changed by assignmentbeyond the current length • var a = new Array(); // a.length == 0 (no elements defined) • a = new Array(10); // a.length == 10 (empty elements 0-9 defined) • a = new Array(1,2,3); // a.length == 3 (elements 0-2 defined) • a = [4, 5]; // a.length == 2 (elements 0 and 1 defined) • a[5] = -1; // a.length == 6 (elements 0, 1, and 5 defined) • a[49] = 0; // a.length == 50 (elements 0, 1, 5, and 49 defined) • Arrays are sparse: space is only allocated for elements that have been assigned a value • Example: myArray[50000] = 3;is perfectly OK • But indices must be between 0 and 232-1 • Multidimensional Arrays • Just array of arrays: var a = [ ["red", 255], ["green", 128] ]; var b = a[1][0]; // b is now "green"

  46. Arrays and objects • Arrays are objects • car = { myCar: "Samand", 7: "Mazda" } • car[7]is the same ascar.7 • car.myCaris the same ascar["myCar"] • If you know the name of a property, you can use dot notation: car.myCar • If you don’t know the name of a property, but you have it’s name in a variable (or can compute it), you must use array notation: car["my" + "Car"]

  47. Array functions… • If myArray is an array, • myArray.sort()sorts the array alphabetically • myArray.sort(function(a, b) { return a - b; }) sorts numerically // Returns < 0, 0, or > 0, depending on order • myArray.reverse()reverses the array elements

  48. Array functions (cont.) • myArray.push(…)adds any number of new elements to the end of the array, and increases the array’s length • myArray.pop()removes and returns the last element of the array, and decreases the array’s length • myArray.unshift() (append) and myArray.shift() (remove) perform the same operations at the beginning of the array • myArray.toString()returns a string containing the values of the array elements, separated by commas • myArray.join() method converts all the elements of an array to strings and concatenates them.

  49. The for…instatement • loop through all the properties of an object with for (variableinobject) statement; for(var prop in course) {document.writeln(prop + ": " + course[prop]); } • course["teacher"]is equivalent to course.teacher • You must use brackets if the property name is in a variable • Possible output: teacher: Mr. xyz number: IT402 • The properties are accessed in an undefinedorder • If you add or deletethe properties of the object within the loop, it is undefined whether the loop will visit those properties • Arrays are objects; • applied to an array, for…in will visit the "properties" 0, 1, 2, …

  50. The with statement document.myForm.result.value = compute(document.myForm.myInput.value); • a lot of typing! With (object)statement;; • uses the object as the default prefix for variables in the statement with (document.myForm) {result.value = compute(myInput.value);}

More Related