610 likes | 1.07k Views
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?.
E N D
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? • 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)
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
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
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
JavaScript embedding in HTML • Directly embedded <script type=“text/javascript”> <!-- …Javascript here… --> </script>
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);
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
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
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>
JavaScript: Changing the Content of HTML Elements • Example x = document.getElementById("demo"); //Find an HTML elementx.innerHTML = "Hello JavaScript"; //Change the content
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">
JavaScript: Changing HTML Styles (CSS) • Example x = document.getElementById("demo"); //Find an HTML element x.style.color = "#ff0000"; //Change the style
Outline • Overview of JavaScript • JavaScript basics • JavaScript Primitives • JavaScript Objects • Control statements • Object Creation and modification • Arrays • Functions • Regular Expressions
General Syntactic Characteristics • Variables • Start with $, _, letter • Case sensitive • Statements can be terminated with a semicolon • Reserved words (25 words) • Comments (same as Java) • // • /* … */
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
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.
Example Properties car.name = Fiatcar.model = 500car.weight = 850kgcar.color = white Methods car.start()car.drive()car.brake()
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:
Example • person=new Object();person.firstname="John";person.lastname="Doe";person.age=50;person.eyecolor="blue";
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
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!
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");
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?");
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?", "");
Outline • Overview of JavaScript • JavaScript basics • JavaScript Primitives • JavaScript Objects • Control statements • Object Creation and modification • Arrays • Functions • Regular Expressions
Primitive Types • Five primitive types • Number • String • Boolean • Undefined • Null
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
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: + - * / % ++ -- = += -= *= /= %=
String Literals (or type) • A String literal is delimited by either single or double quotes • There is no difference between single and double quotes
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
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
Outline • Overview of JavaScript • JavaScript basics • JavaScript Primitives • JavaScript Objects • Control statements • Object Creation and modification • Arrays • Functions • Regular Expressions
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
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)
Outline • Overview of JavaScript • JavaScript basics • JavaScript Primitives • JavaScript Objects • Control statements • Object Creation and modification • Arrays • Functions • Regular Expressions
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
switch Statement Syntax switch (expression) { case value_1: // statement(s) case value_2: // statement(s) ... [default: // statement(s)] }
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)
Outline • Overview of JavaScript • JavaScript basics • JavaScript Primitives • JavaScript Objects • Control statements • Object Creation and modification • Arrays • Functions • Regular Expressions
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
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
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
Outline • Overview of JavaScript • JavaScript basics • JavaScript Primitives • JavaScript Objects • Control statements • Object Creation and modification • Arrays • Functions • Regular Expressions
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
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
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