javascript notes
play

Javascript Notes E-Applications Spring 2015 M. Lampis - PowerPoint PPT Presentation

Javascript Notes E-Applications Spring 2015 M. Lampis Acknowledgment The material on these slides follows the excellent book Speaking JavaScript by Axel Rauschmayer http://speakingjs.com/es5/ Introduction Javascript is a


  1. Javascript Notes E-Applications Spring 2015 M. Lampis

  2. Acknowledgment ● The material on these slides follows the excellent book “Speaking JavaScript” by Axel Rauschmayer ● http://speakingjs.com/es5/

  3. Introduction ● Javascript is a scripting language (doh!) ● Dominant for client-side web programming ● We will be using it inside a modern browser (e.g. Firefox) ● All modern browsers come with a javascript engine ● Javascript is (generally) an interpreted language: the user is given the source code

  4. Relationship with other languages ● Javascript is not really related to Java. – There are some common points between the two – Syntax is similar to C-family languages (C++/Java) ● Javascript is more functional – Similar to Lisp/Scheme in some respects ● Javascript is relaxed with types ● Javascript is relaxed with objects

  5. Up and running ● Basic way to run a javascript program – Include in an HTML file, between <script> </script> tags. < s c r i p t > a l e r t ( “ H e l l o w o r l d ” ) ; < / s c r i p t > ● C a n a l s o u s e t h e j s c o n s o l e o f a b r o w s e r – I n F i r e f o x C t r l + S h i fu + K

  6. Basic Structure ● A js program is a series of statements – Statements should be separated by ; – This is (tried to be) done automatically! (more later) ● Statements resemble Java: – if ( condition ) { statement } else {statement} – for ( var i=0 ; i<5; i++) { statement } – while() { }, do { } while(); – switch() { }

  7. Basic Structure ● Variables must (should) be declared with the var keyword v a r x = 5 ; ● Observe that no type is specified, this is found in run-time and can change. x = ' a b c ' ; / / n o p r o b l e m

  8. Basic Structure ● Arrays use C-like notation v a r a r r = [ ' a ' , 2 , ' c ' ] ; / / d i fg e r e n t t y p e s O K a r r . l e n g t h = = 3 a r r [ 2 ] = = ' c ' ● Elements are indexed from 0 up to arr.length-1 ● OK to add elements! a r r [ 3 ] = ' d ' ; / / a r r = = [ ' a ' , 2 , ' c ' , ' d ' ]

  9. Basic Structure ● Objects in js are more like maps/dictionaries than Java objects ● Again the . (dot) operator is used to access methods/properties v a r m y o b j = { } ; / / e m p t y o b j e c t v a r o b j 2 = { k e y 1 : ' v a l 1 ' , k e y 2 : 1 5 } ; o b j 2 . k e y 2 = = 1 5 / / t r u e o b j 2 . k e y 3 = ' h e l l o ' ; / / O K t o a d d fj e l d s ! ● Object/Array variables are references (Java-like?) ● Arrays are objects! (verify with typeof )

  10. Basic Structure ● Functions are declared using the function keyword f u n c t i o n f a c t ( n ) { i f ( n < 1 ) r e t u r n 1 ; r e t u r n n * f a c t ( n - 1 ) ; } ● Argument types are not specified

  11. Basic Web Page Interaction ● JS programs have a “global” object – For programs running in a browser → window ● Inside window object one finds the document object – This gives methods to access HTML elements – More details to be discussed later (DOM) – Important to know: document.getElementById(“..”) method that returns a reference to an HTML element

  12. Basic Web Page Interaction ● Annoying input output – alert(“msg”); (no return value) – confirm(“msg”); (boolean return) – prompt(“msg”,”default”); (string return) ● Less annoying – Give an id to an input textbox – Access via document.getElementById().value

  13. Basic Web Interaction ● Event-driven programming – Basic idea: the web page waits for the user to do something (generate an event) and respond ● Events: – Mouse click, mouse movement, window resizing, … ● Events can be caught by adding appropriate attributes to the relevant HTML tags < i n p u t t y p e = ” b u tu o n ” o n c l i c k = ” s o m e j s ../ ” / >

  14. More Javascript ● In the remainder we give some more details on various useful features of javascript ● Emphasis on points of difference with other, more familiar languages (Java)

  15. Strings ● One of the primitive data types in js v a r x = “ a b c d ” ; ● Can use either kind of quotes (“ or ') – Be consistent! ● \ is an escape character – ex. x = ' H e \ ' s u s i n g q u o t e s ! ' ; ● No “char” type for single characters (everything is a string)

  16. String functionality ● Strings are not references ● String literals are immutable a = " a b c " ; / / - > " a b c " a [ 2 ] = ' d ' ; / / “ i g n o r e d ” , a = = “ a b c ” ; ● Expressions that produce a new string are OK a += 'd'; // a == “abcd”; ● Note the array-like access – This can be done with .charAt(i) method also

  17. String Conversions ● Other values can be converted to strings, usually easily ● Manual way: S t r i n g ( e x p r ) ; – ' ' + e x p r ; / / D i r t y ! ● Note that conversions are inconsistent sometimes B o o l e a n ( S t r i n g ( f a l s e ) ) ! = f a l s e / / ?@ ?

  18. String Operators ● Comparisons ( <, >, <=, >=, ===) – Work OK (alphabetically) – Not reliable for international characters (accents etc.), use localeCompare ' é ' . l o c a l e C o m p a r e ( ' f ' ) / / g i v e s - 1 ● + performs concatenation ● .length gives the length of a string

  19. String Operations ● The .split method splits a string into an array of strings, using the given separator ' a b c ' . s p l i t ( ' ' ) ; / / → A r r a y [ " a " , " b " , " c " ] ● The separator can also be a regular expression (very useful, see later) ● .toUpperCase, toLowerCase (self-explanatory) ● .indexOf( sth ) finds the index where sth appears in a string (could be -1, sth could be reg ex)

  20. Booleans ● true or false values ● Operators &&, ||, ! ● Careful with conversions: B o o l e a n ( 0 ) = = f a l s e , B o o l e a n ( 1 2 3 ) = = t r u e B o o l e a n ( ' ' ) = = f a l s e , B o o l e a n ( ' a ' ) = = t r u e B o o l e a n ( [ ] ) = = t r u e ( ! ) / / a l l a r r a y s B o o l e a n ( { } ) = = t r u e ( ! ) / / a l l o b j e c t s

  21. Booleans ● Logical operators are short-circuited – f a l s e | | x = = = x ; t r u e & & x = = = x ; ● Application: setting default value to a parameter f u n c t i o n f ( x , y , z ) { y = y | | s o m e _ v a l u e ; ../ } ● Uses the fact that undefined is converted to false ● NOTE: This may not be what you want! (ex. If y = 0) ● Recall also ternary operator x ? y : z

  22. Numbers ● No distinction between ints and floats ● Standard operators +, -, *, /, % ● Standard function Math.abs(), Math.floor(), Math.round() ● Number( expr ) → convert expr to number ● parseInt ( expr ) → convert expr to STRING then integer ● Specials: NaN (never equal to anything!), Infinity

  23. Non-primitive types ● We have seen the primitive types – String – Boolean – Number ● Everything else is non-primitive – Object (also arrays and reg exps) – Function – Undefined (this is a special type!)

  24. Arrays ● Arrays are objects! (see with typeof) ● ...with many useful properties pre-defined – arr.length gives the length of an array – Can be used to shorten/lengthen array! – We can also use .push() to add an element to the end of an array and .pop() to remove it.

  25. Arrays with holes and more ● It's allowed to have some “missing” (undefined) positions in an array. ● These are called holes. ● → Arrays are maps ● Usually, arrays without holes are optimized → faster ● Arrays are also allowed to have arbitrary properties (they are objects)

  26. 2-d Arrays ● 2dimensional arrays can be defined indirectly: ● Construct an array rows – Each element of this array should be an array – Now possible to say rows[2][3] = 5; ● Exercise: construct and print a 2-d array of size 3x3 with the numbers 0,1,...,8

  27. Array operators ● The in operator checks if a given index exists/is not a hole – This will also return true for non-index properties (can be used for objects) ● Can be used to iterate through an array – f o r ( v a r k e y i n a r r ) { d o s t h w i t h a r r [ k e y ] ; } ● Bad idea! – Skips holes (maybe not bad?) – Iterates through other keys (?)

  28. Array Iterations ● Standard (C/C++/Java) way – f o r ( v a r i = 0 ; i < a r r . l e n g t h ; i + + ) { ../ } ; ● Use the forEach method (only available for arrays, not array-like objects such as strings) – a r r . f o r E a c h ( a l e r t ) ; / / N O T a r r . f o r E a c h ( a l e r t ( ) ) ; – Argument is a function that is to be applied to each element of the array – Skips holes

Recommend


More recommend