Presentation is loading. Please wait.

Presentation is loading. Please wait.

JavaScript for C++ and Java Programmers

Similar presentations


Presentation on theme: "JavaScript for C++ and Java Programmers"— Presentation transcript:

1 JavaScript for C++ and Java Programmers
Enough to get you started Copyright © by Curt Hill

2 Copyright © 2005-2017 by Curt Hill
Introduction JavaScript may be the most popular language on the planet It rated 8th on Tiobe index (8/2017) but that is based on larger projects Most JavaScript code is small snippets in HTML Not a good choice for projects: Not on the web Large Needing efficiency and robustness Very popular in web pages Copyright © by Curt Hill

3 Copyright © 2005-2017 by Curt Hill
Characteristics JavaScript has both similarities and differences with C++ or Java What we want to consider today is the differences between JavaScript and these Like many scripting languages JavaScript is interpreted Usually by a web browser Makes programming environment free and easy Copyright © by Curt Hill

4 Copyright © 2005-2017 by Curt Hill
Short History Developed by Netscape as LiveScript about 1995 Netscape and Sun cooperated and renamed it JavaScript The European Computer Manufacturers Association (ECMA) got involved with a standard which gives it the third name ECMAScript MicroSoft originally preferred Jscript, but later changed It is radically different from Java Copyright © by Curt Hill

5 Copyright © 2005-2017 by Curt Hill
How different? Object-based, interpreted language Does not have classes Objects are used as variables and models of other objects It has prototype based inheritance Simulates some aspects of inheritance No polymorphism No typing A variable may change types dynamically Copyright © by Curt Hill

6 Copyright © 2005-2017 by Curt Hill
Variables In Java/C++ a primitive is a memory location with a single type In JavaScript it is more like a pointer to a descriptor The descriptor determines size and type Thus a variable only has the type of the last assignment Copyright © by Curt Hill

7 Copyright © 2005-2017 by Curt Hill
JavaScript in HTML JavaScript may be embedded in either the Head or Body tag of HTML Head script Usually an event handler or other subroutine Usually existence is noted for later use Body script Executed immediately Copyright © by Curt Hill

8 Copyright © 2005-2017 by Curt Hill
Script Tag The script tag has one parameter: the language: <script language=“javascript”> This is ended by a </script> tag Unlike the applet tag, there is no clause for what to do if the browser does not support JavaScript Thus the script is usually within HTML comments Copyright © by Curt Hill

9 Copyright © 2005-2017 by Curt Hill
Form of tags The script occurs as a tag and comment: <script language="javascript"> <!-- /* the program */ // --> </Script> The comments are not needed if we can be sure that the browser accepts JavaScript Copyright © by Curt Hill

10 Copyright © 2005-2017 by Curt Hill
Hello 1 <HTML> <HEAD> <TITLE>JavaScript Demo</TITLE> </HEAD> <BODY> <H1><CENTER> JavaScipt Hello World </CENTER></H1> <P>Here is the slot.<P> Copyright © by Curt Hill

11 Copyright © 2005-2017 by Curt Hill
Hello 2 <HR> <script language="javascript“> <!– HTML Comment document.write("<P><B>Hello World</B>"); // --> </Script><HR> <P>Thats it. </BODY> </HTML> Copyright © by Curt Hill

12 Copyright © 2005-2017 by Curt Hill
How it shows Copyright © by Curt Hill

13 Copyright © 2005-2017 by Curt Hill
Including JavaScript There are two parameters for separate file inclusion Type gives a MIME type SRC gives the file location Example: <script type="text/javascript" src = "t1.js"> </script> Facilitates reuse but causes another browser load Copyright © by Curt Hill

14 Overview of JavaScript
JavaScript is made to look like Java Statements end with a semicolon Words are case sensitive Reserved, predefined or user-defined An examination of reserved words will show considerable similarity with Java However, object model is quite different, as is variable typing Copyright © by Curt Hill

15 Copyright © 2005-2017 by Curt Hill
Some Reserved Words break case catch continue default delete do else finally for function if in instanceof new return switch this throw try typeof var void while with Copyright © by Curt Hill

16 Copyright © 2005-2017 by Curt Hill
Types JavaScript has five basic types Number String Boolean Undefined Null Basics (aka primitives) are stored on the stack and objects on the heap Objects have properties and methods as is normal Primitives may have methods as well Copyright © by Curt Hill

17 Copyright © 2005-2017 by Curt Hill
Dynamic typing This means that any variable may be assigned any value or type of value A variable assumes the type of its most recent assignment A variable may be declared using the var reserved word: var xyz, abc; This may include an initialization: var counter = 0; Copyright © by Curt Hill

18 Copyright © 2005-2017 by Curt Hill
Variables Variables must start with a letter or underscore or dollar No length restrictions Like Java there are conventions May be ignored One is that variable names have no upper case letters Variables do not need to be declared An assignment to an undefined variable forces its declaration Copyright © by Curt Hill

19 Assignments and Expressions
Similar to C++/Java Assignments are the same except no need for type compatibility Same operators, including side effect operators A variable not initialized has the undefined type Since there are no char types a string may be enclose in apostrophes as well as quotes Copyright © by Curt Hill

20 Copyright © 2005-2017 by Curt Hill
Coercion JavaScript will coerce more things than C++ or Java The + will force either string or number depending on the context “ABC”+10 converts the numeric 10 to “10” and concatenates true + 10 gives 11 Numeric operators “10” * “8” requires both to be numeric, so will coerce string to numeric Copyright © by Curt Hill

21 Copyright © 2005-2017 by Curt Hill
typeof operator Most scripting languages may ask the type of an item typeof expr The typeof operator will return a string This string will be one of the five basic types document.write(typeof (4*3)) gives “number” High precedence Copyright © by Curt Hill

22 Copyright © 2005-2017 by Curt Hill
The JavaScript Cast The form of a cast is the type looking like a function, similar to a C++ cast: Number(a) String(b) Boolean(c) Notice that the type is capitalized In contrast to result of typeof Why would you want to cast something as undefined or null? Copyright © by Curt Hill

23 Copyright © 2005-2017 by Curt Hill
toString Numbers have a method for explicit conversion to a string If no parameters then the same as a cast: a = 5; b = String(a); // is same as c = a.toString(); If toString has an argument that is the number base Copyright © by Curt Hill

24 Copyright © 2005-2017 by Curt Hill
Bases Consider var a = 28; document.write(“<P> “ a.toString(); document.write(“<P> “ a.toString(2); document.write(“<P> “+a.toString(16); Will show: c Copyright © by Curt Hill

25 Copyright © 2005-2017 by Curt Hill
The If Similar to the C/C++ if more so than Java Usual comparison operators, Boolean operators and precedence Optional else is same Compound statements are the same JavaScript coercion allows more kinds of things to be compared if(5 == “5”) works and is true Copyright © by Curt Hill

26 Copyright © 2005-2017 by Curt Hill
Two more There are two additional comparison operators === and !== These are strict comparisons No type conversions are attempted Two items may only be equal if they are both of the same type and have same value Thus “5”===5 is false Copyright © by Curt Hill

27 Copyright © 2005-2017 by Curt Hill
String Operands Strings may be freely compared The comparison is case sensitive Compare identical indices starting at beginning First non equal determines the comparison Copyright © by Curt Hill

28 The JavaScript Boolean Convention
Numerics If the value was zero means false Otherwise true String If the length > zero true Empty string false null and undefined mean false Any object is a true Not quite C/C++ but close Copyright © by Curt Hill

29 Copyright © 2005-2017 by Curt Hill
Object comparisons Object comparisons are comparing the handle, not the value So two objects with identical values may compare not equal Generally only when there has been a direct assignment of one object to another will equality give a true This quite similar to Java, where all objects use handles Copyright © by Curt Hill

30 Copyright © 2005-2017 by Curt Hill
Scope Rules The scope rules are different than either Java or C++ Two level scope Things in functions Globals Local variables may be declared anywhere but they are not confined to compound statements Copyright © by Curt Hill

31 Copyright © 2005-2017 by Curt Hill
Switch Similar to what you know, with a more liberal attitude on what can be the selector Strings and reals are legal Still have parenthesized selector Case followed by constant Break Default Copyright © by Curt Hill

32 Copyright © 2005-2017 by Curt Hill
Looping The C style for, while and do are in their original form and function The break and continue also work There is also a for in which is a little different than the Java for all/every We can say: for(x in person){…} Where person is any collection type, such as an array Copyright © by Curt Hill

33 Copyright © 2005-2017 by Curt Hill
Functions Modified version of C function based on dynamic typing Starts with reserved word function, followed by name and parameter list No types on the parameters Return determines the type of the function Variables defined in the function are local Calling looks like any Java call Parameter are by value – like Java Copyright © by Curt Hill

34 Copyright © 2005-2017 by Curt Hill
Output JavaScript is not a stand-alone language It is interpreted by the browser and uses the browser The browser contains the document and JavaScript may access this document This is called DOM Document Object Model Document is the name of this object Copyright © by Curt Hill

35 Copyright © 2005-2017 by Curt Hill
DOM The document object has a variety of properties and methods The DOM refers to pieces of the HTML as node Every HTML tag is a node Today, we are only interested in two methods: write and writeln These write into the document This is how things are displayed Copyright © by Curt Hill

36 Copyright © 2005-2017 by Curt Hill
Write and Writeln Both take one or more arguments They insert that into the document The browser then displays it Write does not finish the line but writeln does Since browser ignore physical end of line, we should write text with HTML tags as needed We may also write the <br/> tag to start a new line Copyright © by Curt Hill

37 Copyright © 2005-2017 by Curt Hill
Structured Data JavaScript has two types of structured data Objects Must be allocated with new Similar to but different from Java objects and any other that you have seen Awaits subsequent presentation Arrays Consider next Copyright © by Curt Hill

38 Copyright © 2005-2017 by Curt Hill
Arrays Similar but not identical to Java Have a length property Mark of array is the brackets [ ] for the subscript Declared with array reserved word JavaScript calls them arrays but they are actually maps Not contiguous storage Anything can be used as subscript We commonly use the in form of the for loop on arrays Copyright © by Curt Hill

39 Copyright © 2005-2017 by Curt Hill
Array Allocation Two step for objects or basics Allocate the array handle This determines the size of the array Allocate (or initialize) the individual elements Primitives need to be initialized Objects are usually initialized by the constructor In either case, usually done with a for often with an in Copyright © by Curt Hill

40 Copyright © 2005-2017 by Curt Hill
Allocation examples Two ways to allocate and initialize New and assignment var x = new Array(5); for (i = 0;i<5;i++) … or for(z in x) … Implied new and array var y = [0,0,0,2,5]; Note the differences from C/C++/Java Copyright © by Curt Hill

41 Copyright © 2005-2017 by Curt Hill
Constant Arrays Constant arrays are bracketed lines = [“hello”, “goodbye”]; This form only works for Strings or things that do not need a new The new is required for objects: var ds = [new Date(), new Date(2008,2,1), new Date(2005,12,12)]; Copyright © by Curt Hill

42 Copyright © 2005-2017 by Curt Hill
Subscripting Using a subscript an element is obtained a[2] = 5; a[k] = a[j+2]-2; Anywhere a variable can be used a[k] can be used First element has subscript zero Last element has subscript size minus one Mostly Copyright © by Curt Hill

43 Copyright © 2005-2017 by Curt Hill
Subscript Errors Suppose: a = new Array(10); a[k] = 2; If k is less than zero or greater than 9 a subscript error occurs Nah! What actually happens is that uninitialized values have the undefined type This is true for subscript errors as well No real error Copyright © by Curt Hill

44 Consider the following
var ar = new Array(), d1 = new Date(), d2 = new Date(2007,12,14); ar[d1] = "Today"; ar[d2] = 12; ar["Hello"] = "Goodbye"; ar[5] = "Five"; ar[true] = "True has been set"; Does this look like an array to you? Copyright © by Curt Hill

45 Copyright © 2005-2017 by Curt Hill
Display of Arrays An array like most objects has a toString method This will attempt to convert the array into a string The string representation will only show items that have a common integer subscript The better way is to use for-in Copyright © by Curt Hill

46 Copyright © 2005-2017 by Curt Hill
Other for loop If arrays had only numeric subscripts we could process every array with a standard for loop Since that is not the case, how do we iterate through one of these The alternate for loop This for provides the index not the value See next slide Copyright © by Curt Hill

47 Copyright © 2005-2017 by Curt Hill
Example var ar = new Array(), d1 = new Date(), d2 = new Date(2007,12,14); ar[d1] = "Today"; ar[d2] = 12; ar["Hello"] = "Goodbye"; ar[5] = "Five"; ar[true] = "True has been set"; for(x in ar){ document.write("<P> type of x “ typeof x); document.write("<P>Index "+x " gives "+ar[x]); } Copyright © by Curt Hill

48 Copyright © 2005-2017 by Curt Hill
Array Methods There are several besides toString sort concat every filter indexOf and lastIndexOf join map push and pop reverse Copyright © by Curt Hill

49 Copyright © 2005-2017 by Curt Hill
Finally That is the brief look at JavaScript There is more to know and this may be covered in another presentation Most important is the objects Are you ready to code JavaScript? Copyright © by Curt Hill


Download ppt "JavaScript for C++ and Java Programmers"

Similar presentations


Ads by Google