1 / 58

Introduction to JavaScript

Introduction to JavaScript . Outline. Overview of JavaScript JavaScript basics JavaScript Primitives JavaScript Objects Control statements Object Creation and modification Arrays Functions Regular Expressions. Client Side. Server Side. WWW. What is JavaScript?.

joanna
Download Presentation

Introduction to 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. Introduction to JavaScript

  2. Outline • Overview of JavaScript • JavaScript basics • JavaScript Primitives • JavaScript Objects • Control statements • Object Creation and modification • Arrays • Functions • Regular Expressions

  3. Client Side Server Side WWW

  4. What is JavaScript? • a lightweight programming language (scripting) • used to make web pages interactive • a web standard (can be executed by all types of web browsers. ) • NOT related to Java other than by name and some syntactic similarities • Originally developed by Netscape (named LiveScript)

  5. Differences between JavaScript and Java • interpreted, not compiled • more relaxed syntax and rules • fewer and "looser" data types • variables don't need to be declared • key construct is the function rather than the class • (more procedural less object-oriented) • contained within a web page and integrates with its HTML/CSS content

  6. Event-Driven Computation

  7. Linking to a JavaScript file • JavaScript can be embedded or linked to an HTML document. • Two locations for JavaScript embedding depends on the purposes (head/body) • JavaScript in the head element will react to user input and be called from other locations • JavaScript in the body element will be executed once as the page is loaded • JavaScript code can be enclosed in HTML comments

  8. Linking to a JavaScript file • Syntax • <script src="filename" type="text/javascript"></script> • Ex. • <script src="example.js" type="text/javascript"></script> • should be placed in HTML page's head • script code is stored in a separate .jsfile

  9. JavaScript embedding in HTML • Directly embedded <script type=“text/javascript”> <!-- …Javascript here… --> </script>

  10. JavaScript Statements • In HTML, JavaScript is a sequence of statements that can be executed by the web browser. • Example var a = 3;var b = 4;var c = a + b;alert(c);

  11. JavaScript Comments • JavaScript comments can be used to make the code more readable. • JavaScript comments can be written as plain text after double slashes (//). • Example • var a = 3;       // Assign 3 to the variable avar b = 4;       // Assign 4 to the variable bvar c = a + b;   // Assign the sum of a and b to the variable calert(c);        // Display the value of c in a message box

  12. JavaScript: Write to the HTML Output • JavaScript can be used to write directly to the HTML output. • Example document.write("<h1>This is a heading</h1>");  // Writes a headingdocument.write("<p>This is a paragraph</p>");  // Writes a paragraph

  13. JavaScript: Calling Functions and Reacting to Events • JavaScript code can be written to call a function as a result of an HTML event. • Example <button type="button" onclick="myFunction()">Click Me!</button>

  14. JavaScript: Changing the Content of HTML Elements • Example x = document.getElementById("demo");  //Find an HTML elementx.innerHTML = "Hello JavaScript";     //Change the content

  15. JavaScript: Changing the Value of HTML Attributes <script> function changeImage() { element = document.getElementById('myimage'); if (element.src.match("bulbon")) { element.src = "pic_bulboff.gif"; } else { element.src = "pic_bulbon.gif"; } } </script> <img id="myimage" onclick="changeImage()" src="pic_bulboff.gif" width="100" height="180">

  16. JavaScript: Changing HTML Styles (CSS) • Example x = document.getElementById("demo");  //Find an HTML element x.style.color = "#ff0000";            //Change the style

  17. Outline • Overview of JavaScript • JavaScript basics • JavaScript Primitives • JavaScript Objects • Control statements • Object Creation and modification • Arrays • Functions • Regular Expressions

  18. General Syntactic Characteristics • Variables • Start with $, _, letter • Case sensitive • Statements can be terminated with a semicolon • Reserved words (25 words) • Comments (same as Java) • // • /* … */

  19. Object Orientation and JavaScript • JavaScript is not an object-oriented programming language, but an object-based • JavaScript defines objects that encapsulate both properties and methods • However, JavaScript does not have true inheritance nor subtyping

  20. JavaScript Objects • Objects are collections of properties • Properties are either data properties or method properties • Properties are values associated with objects. • Methods are actions that objects can perform.

  21. Example Properties car.name = Fiatcar.model = 500car.weight = 850kgcar.color = white Methods car.start()car.drive()car.brake()

  22. Creating JavaScript Objects • Almost "everything" in JavaScript can be objects. Strings, Dates, Arrays, Functions.... • You can also create your own objects. • This example creates an object called "person", and adds four properties to it:

  23. Example • person=new Object();person.firstname="John";person.lastname="Doe";person.age=50;person.eyecolor="blue";

  24. Accessing Object Properties The syntax for accessing the property of an object is: objectName.propertyName This example uses the length property of the String object to find the length of a string: var message="Hello World!";var x=message.length; The value of x, after execution of the code above will be: 12

  25. Accessing Object Methods You can call a method with the following syntax: objectName.methodName() This example uses the toUpperCase() method of the String object, to convert a text to uppercase: var message="Hello world!";var x=message.toUpperCase(); The value of x, after execution of the code above will be: HELLO WORLD!

  26. The alert Method • The alert method opens a dialog box with a message • The output of the alert is notHTML, so use new lines rather than <br/> alert("The sum is:" + sum + "\n");

  27. The confirm Method • The confirm methods displays a message provided as a parameter • The confirm dialog has two buttons: OK and Cancel • If the user presses OK, true is returned by the method • If the user presses Cancel, false is returned var question = confirm("Do you want to continue this download?");

  28. The prompt Method • This method displays its string argument in a dialog box • The dialog box has an area for the user to enter text • The method returns a String with the text entered by the user name = prompt("What is your name?", "");

  29. Outline • Overview of JavaScript • JavaScript basics • JavaScript Primitives • JavaScript Objects • Control statements • Object Creation and modification • Arrays • Functions • Regular Expressions

  30. Primitive Types • Five primitive types • Number • String • Boolean • Undefined • Null

  31. JavaScript Has Dynamic Types • JavaScript has dynamic types. This means that the same variable can be used as different types: • Example var x;               // Now x is undefinedvar x = 5;           // Now x is a Numbervar x = "John";      // Now x is a String

  32. Numeric Literals (or type) • Number values are represented internally as double-precision floating-point values • integers and real numbers are the same type (no int vs. double) • same operators: + - * / % ++ -- = += -= *= /= %=

  33. String Literals (or type) • A String literal is delimited by either single or double quotes • There is no difference between single and double quotes

  34. Other Primitive Types • Null • A single value, null • null is a reserved word • an assignment value, It can be assigned to a variable as a representation of no value. • Using a null value usually causes an error • Undefined • A single value, undefined • However, undefined is not, itself, a reserved word • The value of a variable that is declared but not assigned a value • Boolean • Two values: true and false

  35. Declaring variables • var name = expression; ---------------------------------------------------------- varclientName = “abc xyz"; var age = 32; var weight = 45; ----------------------------------------------------------- • declaring variables: • explicitly, by var keyword (case sensitive) • implicitly, by assignment (give it a value, and it exists!) • types: not specified, but JS does have types ("loosely typed") • common types: Number, Boolean, String, Null, Undefined

  36. Outline • Overview of JavaScript • JavaScript basics • JavaScript Primitives • JavaScript Objects • Control statements • Object Creation and modification • Arrays • Functions • Regular Expressions

  37. Implicit Type Conversion • JavaScript attempts to convert values in order to be able to perform operations • “August “ + 1977 causes the number to be converted to string and a concatenation to be performed • 7 * “3” causes the string to be converted to a number and a multiplication to be performed • null is converted to 0 in a numeric context, undefined to NaN • 0 is interpreted as a Boolean false, all other numbers are interpreted a true

  38. Explicit Type Conversion • parseIntand parseFloat convert the beginning of a string but do not cause an error if a non-space follows the numeric part • converting a String into a Number var name = parseInt("String"); var name = parseFloat("String"); • parseInt("123hello") returns 123 • parseInt(“abcds") returns NaN (not a number)

  39. Outline • Overview of JavaScript • JavaScript basics • JavaScript Primitives • JavaScript Objects • Control statements • Object Creation and modification • Arrays • Functions • Regular Expressions

  40. If/Else Statement if (condition) { statements; } else if (condition) { statements; } else { statements; } ----------------------------------------------- • identical structure to Java's if/else statement • JavaScript allows almost anything as a condition

  41. switch Statement Syntax switch (expression) { case value_1: // statement(s) case value_2: // statement(s) ... [default: // statement(s)] }

  42. Loop Statements • Loop statements in JavaScript are similar to those in Java • While while (control expression) statement or compound statement • For for (initial expression; control expression; increment expression) statement or compound statement • do/while do statement or compound statement while (control expression)

  43. Outline • Overview of JavaScript • JavaScript basics • JavaScript Primitives • JavaScript Objects • Control statements • Object Creation and modification • Arrays • Functions • Regular Expressions

  44. Object Creation and Modification • The new expression is used to create an object • This includes a call to a constructor • The new operator creates a blank object, the constructor creates and initializes all properties of the object • Properties of an object are accessed using a dot notation: object.property • Properties are not variables, so they are not declared • The number of properties of an object may vary dynamically in JavaScript

  45. Dynamic Properties • Create my_car and add some properties // Create an Object object varmy_car = new Object(); // Create and initialize the make property my_car.make = "Ford"; // Create and initialize model my_car.model = "Contour SVT"; • The delete operator can be used to delete a property from an object • delete my_car.model

  46. The for-in Loop • Syntax for (identifier in object) statement or compound statement • The loop lets the identifier take on each property in turn in the object • Printing the properties in my_car: for (var prop in my_car) document.write("Name: ", prop, "; Value: ", my_car[prop], "<br />"); • Result: Name: make; Value: Ford Name: model; Value: Contour SVT

  47. Outline • Overview of JavaScript • JavaScript basics • JavaScript Primitives • JavaScript Objects • Control statements • Object Creation and modification • Arrays • Functions • Regular Expressions

  48. Array Object new Array(10) var name = []; // empty array var name = [value, value, ..., value]; // pre-filled name[index] = value; // store element ------------------------------- var ducks = ["Huey", "Dewey", "Louie"]; var stooges = []; // stooges.length is 0 stooges[0] = "Larry"; // stooges.length is 1 stooges[1] = "Moe"; // stooges.length is 2 stooges[9] = "Curly"; // stooges.length is 10 -------------------------- • two ways to initialize an array • length property (grows as needed when elements added) • Elements of an array do not have to be of the same type

  49. Characteristics of Array Objects • The length of an array is one more than the highest index to which a value has been assigned or the initial size (using Array with one argument), whichever is larger • Assignment to an index greater than or equal to the current length simply increases the length of the array • Only assigned elements of an array occupy space

  50. Array Methods var a = ["Stef", "Amit"]; // Stef, Amit a.push("Brian"); // Stef, Amit, Brian a.unshift("Kenneth"); // Kenneth, Stef, Amit, Brian a.pop(); // Kenneth, Stef, Amit a.shift(); // Stef, Amit a.sort(); // Amit, Stef ---------------------------------------- • methods: concat, join, pop, push, reverse, shift, slice, sort, splice, toString, unshift • push and pop add / remove from back • unshift and shift add / remove from front • sort return the element that is removed

More Related