SEEM4570 System Design and Implementation Lecture 03 JavaScript JavaScript (JS)! Developed by Netscape! A cross platform script language! Mainly used in web environment! Run programs on browsers (HTML is not programmable)! It can be run on the server side also! Node.js is an example! Supposed to call "mocha" or "LiveScript", but changed to "JavaScript" eventually! Netscape wants to continue the success of Java!
JavaScript (JS) (cont'd)! Some typical usages:! Form validation! Handle Events (e.g., when you "click" a button, when you mouse move, etc.)! Animations and visual effects! Manipulate Cookies! A cookie is a small piece of data stored in your computer by the browser when you browse a web page.! Interact with different HTML components! JavaScript (JS) (cont'd)! JavaScript is a Scripting Language! A scripting language is a lightweight programming language.! It does nothing with Java.! Easy to learn.! JavaScript is an Object Oriented Programming Language (as least from my point of view)! Some people may argue with me But that's fine, different people have different opinions, right?! A good article:! http://www.sitepoint.com/oriented-programming-1/
Different Kinds of Programming! In general, there are two kinds of programming:! Procedural Programming! Also known as Imperative Programming! E.g., C! Object Oriented Programming (OOP)! E.g., Java, C++, Objective-C! We will discuss OOP in detail later!! In order to appreciate the powerfulness of OOP, it is better to learn how to write! The <script> Tag! JavaScripts must be written in <script> </script>.! <script> </script> can be put anywhere in <html> </html>.! Try this:! <script> alert("my First JavaScript"); </script> Old examples may write <script type="text/javascript"> instead of <script>. This is no longer required NOW because JavaScript is THE DEFAULT scripting language in ALL modern browsers now.
Writing JS Statement and Semicolon! Each JS statement is a command to the browser. The purpose of the statements is to tell the browser what to do.! Just like any programming language! You can add semicolon (" ; ") or not to add a semicolon at the end of a JS statement! Ending statements with semicolon is optional in JavaScript.! But I recommend you to add semicolon.! Your code will be more clean and easy to follow Writing JS Comments! Similar to C or Java, we use /**/ or // to write comment:! <script> /* This is a comment */ alert("hello"); // This is another comment alert("yeah"); </script>
Writing JS Variables! Like all programming languages, JS also have variables to store data! Unlike C or Java, you do not need to define the data type!! A sample C program:! main(){ int a = 10, b = 12; double pi = 3.1415; char[5] str = "hello";! A sample JS program:! var a = 10, b = 12; var pi = 3.1415; var str = "hello"; Writing JS Variables (cont'd)! For a programming language that do not need to define the data types of the variables, we call these programming has a feature of Dynamic Typing.! Data types of variables will be defined dynamically! E.g. PHP, JS,! Otherwise, if we need to define the data types, we call them Static Typing! E.g. C, C++, Java,
Writing JS Variables (cont'd)! By default, a variable has the value "undefined" if you have not assign anything value to it! Example:! var a = 10; // it has the value 10 var b; // it has the value "undefined"! If you re-define a variable, the previously defined value may not necessarily be overwritten.! Example:! var a = 10, b = 20; var a; var c = a + b; // the result is 30 Writing JS Variables (cont'd)! There are totally 7 different data types:! Boolean! Number! String! Undefined! Null! Array! Object
Data Types Booleans! A Boolean is a logical entity that consists of either a true or a false value:! var x = true;! var y = false; Data Types Number! You do arithmetic same as any programming languages! var a = 10; var b = 20; var pi = 3.1415; var r = a + b; var area = pi * r * r; :! Extra large or extra small numbers can be written with scientific (exponential) notation! var y=123e5; // 12300000! var z=123e-5; // 0.00123
Data Types String! A string can be any text inside quotes. You can use single or double quotes:! var s1 = "Hello", s2 = 'Hello'; // both are CORRECT!! String manipulation in JS is the same as Java:! var s1 = "How"; var s2 = "are"; var s3 = "you?"; var com1 = s1 + s2 + s3; // Output: Howareyou? var com2 = s1 + " " + s2 + " " + s3; // Output: How are you?! You can combine different types of variables as well:! var a = 10, b = 20; var c = a + b; var text = "The result is : "; var final = text + c; // Output: The result is: 30 Data Types Null and Undefined! Variables can be emptied by setting the value to null! var str; // it is undefined. NOT null!!! var str = "hello"; str = null; // set to empty str = 10; // set the value to 10 str = null; // empty it again
Data Types Arrays (1)! You can define it in many ways.! They are equivalent:! var courses = new Array("SEEM4570", "SEEM3490");! var courses = ["SEEM4570", "SEEM3490"];! var courses = new Array(); courses[0] = "SEEM4570"; courses[1] = "SEEM3490";! var courses = []; courses[0] = "SEEM4570"; courses[1] = "SEEM3490"; Data Types Arrays (2)! You can even have your own "key":! They are equivalent:! var courses = []; courses['one'] = "SEEM4570"; courses['two'] = "SEEM3490";! var courses = []; courses.one = "SEEM4570"; courses.two = "SEEM3490";! Note: you should NOT use any number to begin the Key! courses.1 = "SEEM4570" // WRONG! courses.1s = "SEEM4570" // WRONG! courses.s1 = "SEEM4570" // CORRECT
Data Types Objects! Well, this is a bit difficult to understand right now. Let's come back later. Typeof Operator! A less-known operator in JavaScript is the typeof operator. It tells you what type of data you're dealing with:! var booleanvalue = true;! var numericalvalue = 354;! var stringvalue = "This is a String";! var nullvalue = null;! var undefined;! alert(typeof booleanvalue) // displays "boolean"! alert(typeof numericalvalue) // displays "number"! alert(typeof stringvalue) // displays "string"! :
JavaScript as Function! We can write function using JS:! <!DOCTYPE html> <html> <script> function myfunction(){ document.write("<p>this is a paragraph 1</p>"); document.write("<p>this is a paragraph 2</p>"); </script> <body> <script>myfunction()</script> </body> </html> JavaScript as Function (cont'd)! Obviously, we can pass values to and return value from a function:! <script> function calculate(){ var result = (10, 20) alert(result); function sum(a, b){ return a + b; </script>
JavaScript as Function (cont'd)! You can have global and local variables! var pi = 3.1415; function area1(r){ return pi * r * r; function area2(r){ var pi = 22/7; return pi * r * r; alert(area1(10)); alert(area2(10)); JavaScript as Function (cont'd)! There are many predefined functions in JS:! alert()! prompt()! confirm()! :
Notes on JS Programming! Unlike C, but similar to Java, you can define variables anywhere when you like. So! Correct:! for(var i=0; i<100; i++){ Notes on JS Programming (cont'd)! Since JS is dynamic typing if you want to compare BOTH the values and the data types of two variables, you have to use === and!==! Example:! var x = "5", y = 5; alert(x == y); // return true alert(x === y); // return false alert(x!= y); // return false alert(x!== y); // return true
Error Handling! When an error occurs, the JavaScript engine will stop execute immediately.! To have a better error handling, we can use a try-catch strategy:! try{ catch(err){! The program will try to run everything in "try".! If no error occurs, it will ignore anything "catch".! If error occurs anywhere in "try", the program will jump to run everything in "catch" until finished or another error occurs. Error Handling (cont'd)! Example:! try{ var result = sum(10, 20); // the function "sum" is not defined alert(result); catch(err){ alert(err);! Note: you can give any name to the variable "err". E.g.:! catch(err)! catch(e)! catch(exception)
JS and Objects! Technically, "Everything" in JavaScript is Object!!! String, Number, Array,! What's so special about Object?! An object is a piece of data, with properties and methods About Objects! A real life example:! Object! Car! Properties:! Brand: BMW! Model: 330i! Color: Silver Grey! Methods:! Start! Run! Brake
About Objects (cont'd)! Objects in JS, similar to objects in real life objects, may have properties and methods.! For example, the predefined JS object "String"! Properties:! length - The length of a string! Methods:! replace("xx", "yy") Replace string xx to yy for a given string! touppercase() Change all characters to upper case of a give string About Objects (cont'd)! Let's continue our string example:! var str = "Local"; var len = str.length; // len = 5 var str2 = str.replace("l", "V"); // str2 = Vocal var str3 = str.touppercase(); // str3 = LOCAL var str4 = str.replace("l", "V").toLowerCase(); // str4 = VOCAL! Note: when you access the "methods" of an object, you have to put "()" at the end. If you access the "properties", you do not need to do so.
Create You Own Object using JSON! JSON JavaScript Object Notation! Object is delimited by { and. Inside { the properties are defined as name and value pairs (name : value) and separated by commas (, ). Array is defined inside [ ].! Example:! {firstname:"john", lastname:"smith", id:12345, courses: ["seem4570", "seem3490"]! The object (person) in the example above has 4 properties: firstname, lastname, id and courses. Create You Own Object using JSON (cont'd)! To apply JSON in JavaScript:! They are the same:! var person= { firstname : "John", lastname : "Doe", id : 5566, courses: ["seem4570", "seem3550"] ;! To get the values of a property of an object, for example:! var lastname = person.lastname;! var courses = person.courses;! var course = person.courses[1];
Create You Own Object using JSON (cont'd)! You can add method as well:! var person= { // same as previous slide printname: function(){ return this.firstname + + this.lastname; printdetail: function(levelofdetail){ if(levelofdetail >= 1){ return this.id + + this.firstname + + this.lastname; else{ return this.id; ;! Try the following:! person.printname(), person.printdetail(0) and person.printdetail(1) JavaScript Framework! To write JavaScript more efficiently, we will usually use some Framework:! You can think about a Framework is a set of ready-to-use functions and objects, so that we do not need to write everything by ourselves!! One of the most powerful and my favorite JavaScript Framework is jquery
References! JavaScript:! http://www.w3schools.com/js/default.asp! JSON:! http://www.w3schools.com/json/default.asp! http://www.json.org/