Overview of JavaScript Developed by Netscape, as LiveScript Became a joint venture of Netscape and Sun in 1995, renamed JavaScript Now standard of the.

Slides:



Advertisements
Similar presentations
Introducing JavaScript
Advertisements

JS1-1 Introduction to JavaScript (JavaScript 2) Xingquan (Hill) Zhu
The Web Warrior Guide to Web Design Technologies
Outline IS400: Development of Business Applications on the Internet Fall 2004 Instructor: Dr. Boris Jukic JavaScript: Introduction to Scripting.
COS 381 Day 19. Agenda  Assignment 5 Posted Due April 7  Exam 3 which was originally scheduled for Apr 4 is going to on April 13 XML & Perl (Chap 8-10)
12-Jun-15 JavaScript Language Fundamentals I. 2 About JavaScript JavaScript is not Java, or even related to Java The original name for JavaScript was.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
Javascript Client-side scripting. Up to now  We've seen a little about how to control  content with HTML  presentation with CSS  Javascript is a language.
Tutorial 10 Programming with JavaScript
Chapter 6 © 2002 by Addison Wesley Longman, Inc. 1 Chapter 6 Sebesta: Programming the World Wide Web.
Cos 381 Day 4. © 2006 Pearson Addison-Wesley. All rights reserved. 4-2 Agenda Exam 1 Corrected –3 A’s, 3 B’s and 2 C’s I have looked at all the assignment.
Cos 381 Day 4. © 2006 Pearson Addison-Wesley. All rights reserved. 4-2 Agenda Questions? Assignment 1 due January 31 (TUESDAY) Discussions on JAVASCRIPT.
Introduction to scripting
WEB DESIGN AND PROGRAMMING Introduction to Javascript.
JavaScript, Fifth Edition Chapter 1 Introduction to JavaScript.
 2003 Prentice Hall, Inc. All rights reserved. CHAPTER 3 JavaScript 1.
Chapter 4 © 2003 by Addison-Wesley, Inc Overview of JavaScript - Originally developed by Netscape, as LiveScript - Became a joint venture of Netscape.
CP476 Internet Computing JavaScript Client-Side Programming 1 1. What is JavaScript –Another script language for both client-side and sever-side programming.
1 Overview JavaScript (Recommended Reading : Programming the World Wide Web, 4 th Edition, Robert W. Sebesta, Chapters 4, 5 – available at Steely Library)
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
Javascript. Outline Introduction Fundamental of JavaScript Javascript events management DOM and Dynamic HTML (DHTML)
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
1 JavaScript in Context. Server-Side Programming.
Tutorial 10 Programming with JavaScript. XP Objectives Learn the history of JavaScript Create a script element Understand basic JavaScript syntax Write.
Tutorial 10 Programming with JavaScript
Chapter 4 The Basics of JavaScript. © 2006 Pearson Addison-Wesley. All rights reserved Overview of JavaScript - Originally developed by Netscape,
 2003 Prentice Hall, Inc. All rights reserved. CHAPTER 3 JavaScript 1.
Chapter 4 © 2010 by Addison Wesley Longman, Inc Overview of JavaScript - Originally developed by Netscape, as LiveScript - Became a joint venture.
Lecture 9 The Basics of JavaScript Boriana Koleva Room: C54
1 Overview JavaScript (Recommended Reading : Programming the World Wide Web, 4 th Edition, Robert W. Sebesta, Chapters 4, 5 – available at Steely Library)
JavaScript - A Web Script Language Fred Durao
4.4 JavaScript (JS) Deitel Ch. 7, 8, 9, JavaScript & Java: Similarities JS (JavaScript) is case-sensitive Operators –arithmetic: unary +, unary.
1 Introduction to Web Application Introduction to Java Script.
Basic Data Types Numbers (integer and floating point)‏ Strings (sequences of characters)‏ Boolean values (true/false)‏
JavaScript Scripting language What is Scripting ? A scripting language, script language, or extension language is a programming language.
Introducing Python CS 4320, SPRING Lexical Structure Two aspects of Python syntax may be challenging to Java programmers Indenting ◦Indenting is.
Chapter 4 © 2005 by Addison Wesley Longman, Inc Overview of JavaScript - Originally developed by Netscape, as LiveScript - Became a joint venture.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
JavaScript, Fourth Edition
JS1-1 Introduction to JavaScript (JavaScript 1) Xingquan (Hill) Zhu
Chapter 4 © 2014 by Pearson Education Overview of JavaScript - Originally developed by Netscape by Brendan Eich, as LiveScript - Became a joint venture.
4. Javascript M. Udin Harun Al Rasyid, S.Kom, Ph.D Lab Jaringan Komputer (C-307) Desain.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
1 JavaScript in Context. Server-Side Programming.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
Part:2.  Keywords are words with special meaning in JavaScript  Keyword var ◦ Used to declare the names of variables ◦ A variable is a location in the.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
Chapter 4 © 2013 by Pearson Overview of JavaScript - Originally developed by Netscape, as LiveScript - Became a joint venture of Netscape and Sun.
Tutorial 10 Programming with JavaScript. 2New Perspectives on HTML, XHTML, and XML, Comprehensive, 3rd Edition Objectives Learn the history of JavaScript.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
Tutorial 10 Programming with JavaScript. 2New Perspectives on HTML, XHTML, and XML, Comprehensive, 3rd Edition Objectives Learn the history of JavaScript.
REEM ALMOTIRI Information Technology Department Majmaah University.
JavaScript and AJAX 2nd Edition Tutorial 1 Programming with JavaScript.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
Basic Objects. Math Object  Math.cos( x ), x in radians  Math.sqrt ( x )  Math.pow ( x, y )  Math.ceil( x )  etc.
4.1 Overview of JavaScript
>> Introduction to JavaScript
4.1 Overview of JavaScript
Chapter 6 JavaScript: Introduction to Scripting
Chapter 4 Basics of JavaScript.
WEB PROGRAMMING JavaScript.
The Basics of JavaScript
PHP.
T. Jumana Abu Shmais – AOU - Riyadh
CS5220 Advanced Topics in Web Programming JavaScript Basics
Tutorial 10 Programming with JavaScript
JavaScript CS 4640 Programming Languages for Web Applications
4.1 Overview of JavaScript
CS3220 Web and Internet Programming JavaScript Basics
JavaScript CS 4640 Programming Languages for Web Applications
Presentation transcript:

Overview of JavaScript Developed by Netscape, as LiveScript Became a joint venture of Netscape and Sun in 1995, renamed JavaScript Now standard of the European Computer Manufacturers Association ECMA-262 (also ISO 16262)

JavaScript Three categories  Core,Client-side,&Server-side Collections of JavaScript code as called scripts Java and JavaScript only related through syntax  JavaScript is dynamically typed  JavaScript's support for objects is very different JavaScript can be embeded in many things, but its primary use is in HTML

JavaScript DocumentObject Model (DOM) makes it possible to support dynamic HTML with JavaScript Promotes user interaction through forms User interactions with HTML documents in JavaScript use the event-driven model of computation  User interaction with form elements can be used to trigger scripts

OO & JavaScript JavaScript is not OO programming language  Does not support class-based inheritance  Cannot support polymorphism  Prototype-based inheritance  Which is much different

JavaScript Objects Objects are collections of properties (like members of the class in Java)  Data properties  Method properties Primitives for simple types JavaScript objects are accessed through references Objects appear as lists of property-value pairs  Properties can be added or deleted dynamically

JavaScript General Syntax Embeded in HTML documents  Directly as the content of tag...  Indirectly as a file specified in the src attribute of script...

JavaScript General Syntax Place scripts inside HTML comments to hide them from bowsers that do not include JavaScript interpreters JavaScriot does not need to be terminated by ;  But it is a good practice to do so

Primitives, Operations & Expressions Primitive values, one of five:  Number, String, Boolean, Undefined, or Null Number, String, and Boolean have wrapper objects: Number, String, & Boolean Primitive values and objects of Number & String are coerced back and forth  Primitive values are treated essentially as if they were objects

Primitives, Operations & Expressions Numeric literals are just as in Java Numeric values are stored in double-precision floating point String literals are delimited by ' or “  Can include scape sequences (\t)  Embedded variable names are not interpolated  String literals are primitive values

Primitives, Operations & Expressions Boolean values are true and false The only value of Null is null The only Undefined value is undefined JavaScript is dynamically typed  Any variable can be used for any thing  Primitive value or reference to any object  The interpreter determines type of each occurrence of a variable

Primitives, Operations & Expressions Variables declared explicitly or implicitly var = sum = 0, today = “Monday”, flag = false ; Numeric operators: ++, - -, +, -, *, /, %  All in double precision The Math object  Floor, round, max, min, trig functions, etc. Assignment opperator – Just like Java

Primitives, Operations & Expressions  The Number object with method toString  Some useful properties: MAX_VALUE, MIN_VALUE, NaN, POSITIVE_INFINITY, NEGATIVE_INFINITY, PI  Number.MAX_VALUE  Arithmetic operation creates overflow returns NaN  NaN is not == to any other number, not even itself  Test for it with isNaN (x)

Primitives, Operations & Expressions  String catenation operator: +  Coercions:  Catenation coerces numbers to strings  Numeric operators (not +) coerce strings to numbers  Conversions from strings to numbers that do not work return NaN

Primitives, Operations & Expressions  String properties & methods: length e.g., var len = str1.length; (a property) charAt(position) e.g., str.charAt(3) indexOf(string) e.g., str.indexOf('B') substring(from, to) e.g., str.substring(1, 3) toLowerCase() e.g., str.toLowerCase()

Primitives, Operations & Expressions  Conversion functions (not called through string objects, because these are not methods)  parseInt (string) and parseFloat (string)  String must begin with a digit or a sign and contain a legal number, otherwise NaN is returned  The typeof operator  Returns “number, “string”, or “boolean” for primitives  Returns “object” for objects and null

Screen Output  The Document object is the JavaScript model for the HTML document  The Window object in the model for the browser display window  Two properties: document, and window  Referring to Document and Window objects

Screen Output  The Document object has a method, write,  Dynamically creates content  Parameter is a string that is sent to the browser  it can be any thing that can appear in HTML including tags  Parameter often catenated from parts some of which are variables document.write(“It is OK” + “to learn about” + “ ”) ;

Screen Output  The Window object has three methods  alert, confirm, and prompt  The default object is the current window  Object need not be included in calls to any of these  A lert( “ Hello World! \n”)  Parameter plain text, not HTML  Opens a dialog box which displays the parameter string and an OK button  Waits for used to press the OK button

Screen Output  C onfirm (“What would you like?”)  Opens a dialog box, displays the parameter and two buttons, OK and cancel  Returns a Boolean  prompt(“What is your pleasure?”,””)  Opens a dialog box, displays the parameter, along with a text box and two buttons, OK and cancel  The second parameter is for default value if the user presses OK without typing any response

Control Expressions  Primitive Values  If it is string, it is true unless it is empty or “0”  If it is a number, it is true unless it is zero  Relational Expressions: ==, !=,, >=, >=  Operands coerced if necessary  String to number / Boolean to number  Unusual: ===, !==  Same as == and !=, except that no coercions are allowed. Operands must be identical

Control Expressions  Compound expressions &&, ||, and !  Primitive values, true and false, not to be confused with Boolean Object properties  Boolean object in a expression is false only when it is null or undefined  Boolean object has a method, toString, to allow them to be printed out.

Selection Statements  If-then-else --Just as in Java  Switch switch (expression) { case value_1: // value_1 statements case value_2: // value_2 statements … [default: // default statements] }

Control Statements  Loop Statements  while(control_expression) Statement or compound  For( int ; control ; increment) Statement or compound  Int can have declaration, but scope is the whole script  do Statement or compound while( control_expression)

Object Creation/Modification  Objects created with new  Most basic object uses the object constructor  Var myobject = new object();  New object has no properties - a blank object  Properties can be added to object at any time var mycar = new object(); mycar.make = "volvo"; mycar.model = "245";

Object Creation/Modification  Objects can be nested. A property can be itself another object created with new. Var property1 = mycar["model"];  Attempting to access non-existing properties yields undefined  Properties can be deleted with delete: delete mycar.model;

Object Creation/Modification  The for-in loop-statement is perfect for listing the properties of an object: for( identifier in object) statement or compound Ex: for( var prop in mycar) document.write(mycar[prop] +" ");

Arrays  Objects having some special functionality  Array elements can be primitive values or references to other objects.  Array objects can be created in two ways:  With new: var mylist = new Array(24,"butter", false);//length is 3. var mylist2 = new Array(24) /* length is 25 */  Assigning an array literal: var mylist3 = [24, "eggs", false];

Arrays  Length is dynamic -length property stores it.  Length is highest subscript to which an element has been assigned, plus 1 mylist[122] = "wee-small"; // length is 123  length property is writeable mylist.length =150; //make it larger mylist.length = 2; //make it shorter  Only assigned elements take up memory space

Array Methods var list = new Array("John","Paul","George","Ringo");  join - var listStr = list.join(": "); listStr contains "John: Paul: George: Ringo"  reverse  sort -coerces elements to strings and puts them in alph order  concat - newList = list.concat(47,26);

Array Methods  slice listPart = list.slice(1,3); // listPart is ["Paul","Ringo"] listPart = list.slice(2); // listPart is ["George","Ringo"]  toString -- exactly as join(", ")  push, pop, unshift, shift

JavaScript Functions function function_name( formal_arguments){... // function_body }  A return statement turns control to caller.  A function returns undefined when:  End of the function is reached, or  Specific return statement executed does not have expression  There are no return statements in the function

Functions  Functions are objects!  Variables that reference them can be treated as any other object reference:  Can be passed as paramenters,  Can be assigned variables,  Can be elements of an array ref_fun = fun; // where fun is the name of a function /* ref_fun is a reference to fun*/ ref_fun(); /* A call to fun */

Functions  All variables declared, implicitly or explicitly, outside functions have global scope.  Variables explicitly declared in a function have local scope.  Local variables have precedence over global variables with the same name.  Functions can be nested - we will not discuss it.

Function Parameters  JavaScript functions parameters are normally passed-by-value.  There is not type checking of parameters.  There is no checking on the number of parameters: excess actual parameters are ignored excess formal parameters are set to undefined.

Function Parameters  All parameters passed through a property array, arguments.  A function can determine the number of actual parameters by accessing arguments.length  Because the arguments array is accessible directly, all actual parameters in the call are available, including the actual parameters that do not correspond to any formal parameters m

Function Parameters  When a reference is passed, the function has access to objects in the calling program. Hence it can also pass-by-reference objects.  There is no clean way to send a primitive by reference Function by10(a){a[0]*=10;}... Var listx = new Array(1); Listx[0] = x; By10[listx); X = list[0];  Alternative, function returns the new value.

The sort method  Sort method coerces elements to strings and puts them in alph order.  To sort something other than strings to alpha ord, write a function that performs the comparison and send it to the sort method.  The comparison must return a negative number if the two numbers are in order, zero if they are equal, positive number if they are not. Function num_order(a, b) {return a-b;} num_list.sort(num_order);

 function median( list){  list.sort(function(a,b){return a-b;});  var list_len = list.length;  if (( list_len %2 == 1 )  return list[Math.floor(list_len / 2)];  else  return Math.round( (list[list_len /2 -1]+  list[list_len /2 ] ) / 2 );  } // End of function median.

Constructors  Methods that create and initialize properties of newly created objects  Constructors are called by the new operator which precedes them in the new expression var array = new Array(100);  Constructor reterences the object with this, a predefined reference variable used to construct and initialize the properties of the object.

Constructors  Example function car(new_make, new_model, new_year){ this.make = new_make; this.model = new_model; this.year = new_year; } my_car = new car("Volvo", "S90", "2002");

Constructors  Methods for the objects are initialized just as if it were a data property: function diplay_car(){ document.write("Car make: ", this.make, " "); document.write("Car model: ", this.model, " "); document.write("Car year: ", this.year, " "); }  Add to the constructor: this.display = display_car;  Now call method: my_car.display();

Pattern Matching Regular Expressions  Pattern matching based on the RegExp object are not covered in this class.  Pattern matching based on methods of the String object are covered.  Methacharacters have special meaning in some contexts in patterns: \ | ( ) [ ] { } ^ $ * + ?.  Normal characters are not methacharacters.

Pattern Matching  search(pattern)  Returns position in the string object where the pattern matched var str = "Hurricane"; var position = str.search(/can/); /* postion is now 5 */  If there is no match it returns-1  The period matches any character except new line. /snow./ matches "snowy", "snowd", etc.

Pattern Matching  Placing desired characters in brackets allows class of characters [abc] matches for 'a', 'b', or 'c' [a-h] matches any lower case letter from 'a' to 'h' [^aeiou] matches any consonant  Repeated character or character-class pattern /xy{4}z/ matches for xyyyyz

Pattern Matching  Predefined Character Classes \d[0-9] A digit \D[^0-9] Not a digit \w[A-Za-z_0-9 ]An alphanumeric character \W[^A-Za-z_0-9] Not an alphanumeric \s[ \r\t\n\f] A whitespace character \S[^ \r\t\n\f] Not a whitespace character \b matches boundary between \w and \W \B matches a non-word boundary, opposite of \b

Pattern Matching  Symbolic quantifiers * zero or more repetitions + one or more repetitions ? one or none repetitions /x*y+z?/ any number of x s, one or more y, may be a z /\d+\.\d*/ a string of one or more digits followed by a decimal period and may be more digits.

Pattern Matching  Anchors  Beginning of string (^): /^pearl/ matches patterns beginning with "pearl..."  Ending of string ($) : /gold$/ matches patterns ending in "... gold"  Note anchor characters only have such meaning in these locations: /A^is$/ matches for /A^is$/ only

Pattern Matching  Modifiers attached to pattters to change how they are used: /ab/i matches for either upper or lower case 'ab' /sp/x allows for white space to appear in the pattern

Pattern Matching  replace (pattern, string)  Replace substrings in the string object that match pattern. Var str = "It rains mostly in the plains"; str.replace(/in/g, "nk"); /* str becomes " It ranks mostly nk the planks " */ $1, $2, $3 predifined variables set to " in " g modifier makes replacement global, every match replaced.

Pattern Matching  match (pattern) Returns array of results of pattern-maching operation  With the g modifier it returns an array of substrigs that matched  Whithout the g modifier, first element of returned array has the matched substring, the other elements have the values of $1,... var str "my 3 kings beat your 2 aces"; var matches = str.match(/[ab]/g); /* matches is set up to ["b", "a", "a"]

Pattern Matching  split (pattern)--splits object string into substrigs based on a given pattern var str = "gouda:brie:raclet"; var cheese = str.split(":"); /* cheese set to [gouda, brie, raclet] */

Debugging JavaScript  IE6  Select Internet Options from the Tools menu  Choose the Advance tab  Uncheck the Disable script debugging box  Check the Display a notification about every script error box  Now a window error causes a small window to be opened with an explanation of the error

Debugging JavaScript  NS6  Select Tasks, Tools, and JavaScript Console  A small window appears to display script erros  To avoid confusion, clear the console after using an error message.