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

javascript notes
SMART_READER_LITE
LIVE PREVIEW

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


slide-1
SLIDE 1

Javascript Notes

E-Applications Spring 2015

  • M. Lampis
slide-2
SLIDE 2

Acknowledgment

  • The material on these slides follows the

excellent book “Speaking JavaScript” by Axel Rauschmayer

  • http://speakingjs.com/es5/
slide-3
SLIDE 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

slide-4
SLIDE 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
slide-5
SLIDE 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

  • w
  • r

l d ” ) ; < / s c r i p t >

  • C

a n a l s

  • u

s e t h e j s c

  • n

s

  • l

e

  • f

a b r

  • w

s e r

– I

n F i r e f

  • x

C t r l + S h i fu + K

slide-6
SLIDE 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() { }

slide-7
SLIDE 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

  • p

r

  • b

l e m

slide-8
SLIDE 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 ' ]

slide-9
SLIDE 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

  • b

j = { } ; / / e m p t y

  • b

j e c t v a r

  • b

j 2 = { k e y 1 : ' v a l 1 ' , k e y 2 : 1 5 } ;

  • b

j 2 . k e y 2 = = 1 5 / / t r u e

  • b

j 2 . k e y 3 = ' h e l l

  • '

; / / O K t

  • a

d d fj e l d s !

  • Object/Array variables are references (Java-like?)
  • Arrays are objects! (verify with typeof)
slide-10
SLIDE 10

Basic Structure

  • Functions are declared using the function

keyword f u n c t i

  • 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
slide-11
SLIDE 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

slide-12
SLIDE 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

slide-13
SLIDE 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

  • n

  • n

c l i c k = ” s

  • m

e j s ../ ” / >

slide-14
SLIDE 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)

slide-15
SLIDE 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

  • t

e s ! ' ;

  • No “char” type for single characters (everything is

a string)

slide-16
SLIDE 16

String functionality

  • Strings are not references
  • String literals are immutable

a = " a b c " ; / /

  • >

" a b c " a [ 2 ] = ' d ' ; / / “ i g n

  • 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

slide-17
SLIDE 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

  • l

e a n ( S t r i n g ( f a l s e ) ) ! = f a l s e / / ?@ ?

slide-18
SLIDE 18

String Operators

  • Comparisons ( <, >, <=, >=, ===)

– Work OK (alphabetically) – Not reliable for international characters (accents

etc.), use localeCompare ' é ' . l

  • c

a l e C

  • m

p a r e ( ' f ' ) / / g i v e s

  • 1
  • + performs concatenation
  • .length gives the length of a string
slide-19
SLIDE 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)

slide-20
SLIDE 20

Booleans

  • true or false values
  • Operators &&, ||, !
  • Careful with conversions:

B

  • l

e a n ( ) = = f a l s e , B

  • l

e a n ( 1 2 3 ) = = t r u e B

  • l

e a n ( ' ' ) = = f a l s e , B

  • l

e a n ( ' a ' ) = = t r u e B

  • l

e a n ( [ ] ) = = t r u e ( ! ) / / a l l a r r a y s B

  • l

e a n ( { } ) = = t r u e ( ! ) / / a l l

  • b

j e c t s

slide-21
SLIDE 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

  • n

f ( x , y , z ) { y = y | | s

  • 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
slide-22
SLIDE 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
slide-23
SLIDE 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!)

slide-24
SLIDE 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.

slide-25
SLIDE 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)

slide-26
SLIDE 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

slide-27
SLIDE 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

  • r

( v a r k e y i n a r r ) { d

  • s

t h w i t h a r r [ k e y ] ; }

  • Bad idea!

– Skips holes (maybe not bad?) – Iterates through other keys (?)

slide-28
SLIDE 28

Array Iterations

  • Standard (C/C++/Java) way

– f

  • r

( v a r i = ; 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

  • r

E a c h ( a l e r t ) ; / / N O T a r r . f

  • 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

slide-29
SLIDE 29

Array methods

  • .sort() will sort the array (doh!)

– Caution! Sorting will first convert elements to strings

→ lexicographic sorting

– Can give an optional function argument that

decides the order of two elements

– [

1 , 2 , 3 , 2 ] . s

  • r

t ( ( f u n c t i

  • n

( x , y ) { x < y ?

  • 1

: ( x > y ? 1 : ) } ) ) ; / / g i v e s [ 1 , 2 , 3 , 2 ]

– [

1 , 2 , 3 , 2 ] . s

  • r

t ( ) ; / / g i v e s [ 1 , 2 , 2 , 3 ]

slide-30
SLIDE 30

Searching

  • .indexOf(elem) returns the first index where

elem occurs, or -1

  • .lastIndexOf(elem) returns the last index
  • Interesting: can never find NaN (since it is not

equal to anything)

  • Uses strict equality === (more later)
slide-31
SLIDE 31

Arrays exercise

  • Write a function that counts the elements of an

array

  • .length will also count the holes...

– Hint: easier with a “temporary” function

slide-32
SLIDE 32

Functions

  • Three roles of functions in javascript

– Normal functions

  • function f(args) {..}; … f(expr);

– Constructors

  • n

e w O b j e c t ( ../ ) ;

– Methods

  • m

y O b j . d

  • S
  • m

e t h i n g ( ../ ) ;

slide-33
SLIDE 33

Function definitions

  • The usual

f u n c t i

  • n

a d d ( x , y ) {

r e t u r n x + y ; / /

  • t

h e r t h i n g s i g n

  • r

e d ../ ( ? )

}

slide-34
SLIDE 34

Function variables

  • We can use a function expression

v a r a d d = f u n c t i

  • n

( x , y ) {

r e t u r n x + y ; / /

  • t

h e r t h i n g s i g n

  • r

e d ../ ( ? )

}

  • Now the typeof add is function
  • These two are almost(!) equivalent
slide-35
SLIDE 35

Hoisting

  • Functions are hoisted

– This means that no matter where in scope a

function is defined it is implicitly moved to the beginning of the scope

  • Variables are hoisted

– Their scope is the whole function (blocks are

ignored)

  • But variable assignments are not hoisted!
slide-36
SLIDE 36

Function expressions

  • Function expressions can be named

– This can make them recursive – v

a r s u p e r f = f u n c t i

  • n

f ( x ) { r e t u r n x < 1 ? 1 : x * f ( x

  • 1

) ; } ;

– Here, f is only accessible within f. – But superf is a variable that can be called from

  • utside

– The name “f” can be accessed with the property

superf.name

slide-37
SLIDE 37

Checking passed parameters

  • Functions can be called with more or less parameters

than defined

– JS will not complain (!)

  • Useful to check the special arguments object

– Array-like (but not array) – .length tells us the number of actual parameters

f u n c t i

  • n

a l e r t A r g s ( ) {

f

  • r

( v a r i = ; i < a r g u m e n t s . l e n g t h ; i + + )

a l e r t ( " a r g " + i + " = " + a r g u m e n t s [ i ] ) ;

}

slide-38
SLIDE 38

Does a parameter exist

  • Easy answer: check if it is undefined

– i

f ( x = = = u n d e fj n e d ) { ../ }

  • Similar

– i

f ( ! x ) { ../ }

  • Recall how to set default values

– x

= x | | d e f a u l t ;

slide-39
SLIDE 39

Pass By Value

  • All function calls are normally pass-by-value

f u n c t i

  • n

i n c ( x ) { x + + ; } ; v a r y = ; i n c ( y ) ; / / n

  • e

fg e c t

  • One workaround: Arrays (which are refs)

f u n c t i

  • n

i n c ( x ) { x [ ] + + ; } ; v a r y = [ ] ; i n c ( y ) ; / / y [ ] = = 1

slide-40
SLIDE 40

Careful with function signatures

  • Meet the .map() method of Arrays

[ 1 , 2 , 3 ] . m a p ( f u n c t i

  • n

( x ) { r e t u r n x + 2 ; } ) ;

  • How about the following?

[ “ 1 ” , ” 2 ” , ” 3 ” ] . m a p ( p a r s e I n t ) ;

  • Tii

s f a i l s b e c a u s e m a p f e e d s t h e g i v e n f u n c t i

  • n

3 p a r a m e t e r s ( e l e m e n t , i n d e x , a r r a y )

  • Tie

f u n c t i

  • n

i n t h e fj r s t e x a m p l e i g n

  • r

e s t h e

  • t

h e r 2

  • p

a r s e I n t d

  • e

s n

  • t
slide-41
SLIDE 41

One caveat for return

  • Recall that ; are automatically inserted where

missing (!)

var x=5 var y=3 //no problem

  • How does JS know when they are missing?

– New line starts unexpectedly – Block ends unexpectedly – ...

slide-42
SLIDE 42

One caveat for return

  • Consider the following:

r e t u r n { f

  • :

“ b a r ” } ;

  • O

r

r e t u r n {

f

  • :

“ b a r ”

} ;

  • Not equivalent!
slide-43
SLIDE 43

The eval function

  • The eval function takes as input a string
  • The string is evaluated as js code

– Similar to writing something on the console – Use case: evaluating arithmetic expressions given by

the user

– Careful: allowing the user to evaluate arbitrary things

may not be a good idea

– On the other hand, this code is running on the client...

slide-44
SLIDE 44

Other problems: dangling else

  • Dangling else problem (also in C/Java)

– i

f ( t e s t 1 ) i f ( t e s t 2 ) { ../ } e l s e { ../ }

  • When is else executed?

– When test1 is false? – When test1 is true and test2 is false?

  • Answer: please use { } to make clear
  • Answer: else is matched to closest if
slide-45
SLIDE 45

Reminder: the switch statement

  • Also present in C/C++

f u n c t i

  • n

u s e F r u i t ( f r u i t ) { s w i t c h ( f r u i t ) { c a s e ' a p p l e ' : m a k e C i d e r ( ) ; b r e a k ; c a s e ' g r a p e ' : m a k e Wi n e ( ) ; b r e a k ; } }

slide-46
SLIDE 46

Reminder: Exceptions

  • Work similarly to Java/C++

t r y {

t h r

  • w

( " O O P S ! " ) ;

} c a t c h ( e x c e p t i

  • n

) {

a l e r t ( e x c e p t i

  • n

)

}

slide-47
SLIDE 47

Regular expressions

  • Can be given between / and /

– Special characters: – ? match 0 or 1 time – * match 0 or more times – + match 1 or more times – . any character – [ ] range/group of characters

  • Examples

– / *, */ → any amount of whitespace that includes a comma – / *,? */ → any amount of whitespace that may include a comma – /[1-9][0-9]*/ → a non-empty integernumber

slide-48
SLIDE 48

An application: split

  • The String split(sep) method splits a string into an array of

strings, using the separator sep

  • sep can be a string or a reg exp
  • Examples:

" 1 , 2 , 3 , 4 " . s p l i t ( " , " ) ; → A r r a y [ " 1 " , " 2 " , " 3 " , " 4 " ] " 1 , 2 , 3 , 4 " . s p l i t ( " , " ) . m a p ( N u m b e r ) ; → A r r a y [ 1 , 2 , 3 , 4 ] " 1 , 2 , 3 , 4 " . s p l i t ( / * , * / ) ; → A r r a y [ " 1 " , " 2 " , " 3 " , " 4 " ]