SlideShare ist ein Scribd-Unternehmen logo
1 von 70
Downloaden Sie, um offline zu lesen
Introduction to JavaScript
                          For
             Modern Software Development


                    Kenneth Geisshirt
                   http://kenneth.geisshirt.dk/




· osd12-js.odp
Agenda – before lunch
●    History and standard
●    Implementations
●    Tools
●    Syntax
●    Procedural programming
●    Object-orientation
●    Functions as first-class object
●    Fluent interfaces
· osd12-js.odp
Tools
●       Syntax highlighting in most editors
●       JSLint is a great code checker
        ●   http://jslint.com/
        ●   Easy to run using Rhino and integrate with Emacs
●       Firebug has a nice Javascript debugger
        ●   http://getfirebug.com/
●       Web developers: use a framework:
    ●   Jquery - http://jquery.com/      ● YUI - http://developer.yahoo.com/yui/

    ●   Prototype - http://prototypejs.org/ Dojo - http://www.dojotoolkit.org/
                                         ●




    ●   Underscore - http://documentcloud.github.com/underscore/
· osd12-js.odp
Agenda – after lunch
●    JavaScript and the browser
      ●    Interaction with DOM
      ●    JSON
      ●    AJAX
●    Moderne web programming
      ●    Jquery
●    Back-end programming
      ●    Node.js

· osd12-js.odp
Features
●    Dynamic
      ●    Extending and modifying a running program
●    Weakly typed
      ●    Implicit type conversion
      ●    Implicit declared variables
●    Prototype-based objects
      ●    Objects but no classes
●    Functions as first-class objects
      ●    A Function is just an object
· osd12-js.odp
History and standard
●    Designed by Brendan Eich (Netscape) in 1995
      ●    Netscape Communicator 2.0b3 (December 1995)
      ●    Internet Explorer 3.0 (August 1996)
●    JavaScript is a Oracle trademark
●    Standardized by ECMA
      ●    Official name ECMAScript
      ●    ECMA-262/ISO-16262 (1997)
      ●    Revision 5.1 is latest revision (June 2011)

· osd12-js.odp
Implementations
●    Closed source
      ●    JScript (Microsoft)
      ●    Futhark (Opera)
●    Open Source
      ●    SpiderMonkey (Mozilla, written in C)
      ●    Rhino (Mozilla, written in Java)
      ●    QtScript (Nokia Troll Tech)
      ●    JavaScriptCore (Apple)
      ●    V8 (Google)
· osd12-js.odp
Future implementations
●    Just-In-Time (JIT) is becoming popular
      ●    V8 is doing it already
      ●    TraceMonkey and JägerMonkey (Mozilla)
      ●    SquirrelFish (Apple)
      ●    Carakan (Opera)
      ●    Tamparin (Adobe and Mozilla)
●    Size does matter (smaller is better)
      ●    Transformation and compression of code
      ●    Google Closure
· osd12-js.odp
Basic syntax




· osd12-js.odp
Syntax – comments and lines
●    Just like C
      ●    The rest of the line: //
      ●    Multi-line: /* */
●    // is recommeded by Javascript developers
●    Statement separator is ; (semicolon)
●    Statements can span multiple lines
●    White spaces: space and tab
●    Case sensitive
· osd12-js.odp
Syntax – literals
●   Booleans
      ●   Examples: true, false
      ●   Other false values: null, NaN, '', 0, undefined
●   Numbers
      ●   Integers
           –     Examples: 42, 101010
      ●   Real numbers
           –     Examples: 3.1415926535, 6.022e23, 6.626e-34
●   Strings
      ●   Examples: “Hello”, 'world', “Don't panic”
· osd12-js.odp
Syntax - names
●    Begin with a letter         Reserved words
      ●    can be followed by    abstract, boolean, break, byte,
           letters, digits and   case, catch, char, const, continue,
           underscores (_)       debugger, default, delete, do,
                                 double, else, enum, export,
      ●    Many                  extends, false, final, float, for,
           implementations       function, goto, if, implements,
                                 import, in, instanceof, int,
           allow dollar and      interface, long, native, new, null,
           underscore as first   package, private, protected,
           character             public, return, short, static, super,
                                 switch, synchronized, this, throw,
                                 throws, transient, true, try, typeof,
                                 var, volatile, void, while, with
· osd12-js.odp
Syntax - expression
                     literal


                     name


                                (      expression   )


                       expression      operator     expression


                       prefix       expression



                                    function call

“hello “+”world”, f(42), 1.0/(x+y), -3.14, 5>7
Example: expr.js
    · osd12-js.odp
Syntax – expression
 ●   typeof(·) returns type of the argument as string
      ●   undefined, boolean, number, string, object, function
 ●   Equality: === and !==
 ●   Inequality: <, >, >=, <=
 ●   Logical: && (and), || (or), ! (not)
 ●   Arithmetic: +, -, *, /, %
 ●   String concatenation: +
 ●   += and -= can be used (but not recommended)
Example: opers.js
· osd12-js.odp
== vs ===
 ●   == compares values
 ●   === compares values and types
 ●   Similar for != and !==
 ●   Recommendation: use === and !==
Example: equal.js




· osd12-js.odp
Arrays
 ●   Two ways to create an array
      ●    Recommended: a = [2.7182, 3.1415]
      ●    a = new Array()
 ●   Zero based index
 ●   Elements do not have to be of the same type
 ●   Indirection by []
 ●   Property length is the number of elements
Example: array.js


· osd12-js.odp
Procedural programming




· osd12-js.odp
Procedural programming


var                   name                     =   expression



                                           ,

●     Declare variables
      ●    Only global name space
      ●    No late declarations
             –   Visible in all function
      ●    Interpreter deduces type at runtime
· osd12-js.odp
Blocks

          {            statements          }




●    Block is similar to blocks in C
      ●    But they do not declare a scope
      ●    Variables are visible before and after the block
      ●    Advice: declare all variables in the top of functions

· osd12-js.odp
Branches

       if         (   expression   )    block    else   block




 ●   Falsy values for an expression:
      ●     false, null, undefined, '', 0, NaN
      ●     All other values are true
Example: if.js


· osd12-js.odp
Other branches
 ●   The switch construct is similar to C
      ●   Case expressions can be variable
      ●   And can be a number or a string
      ●   Each case must be terminated by break
switch (c) {
     case 'A':
            break;
}
Example: switch.js

· osd12-js.odp
Loops
 ●   Four loops constructions exist
      ●    Execute while an expression is true
             –   Zero or more times
      ●    do while an expression is true
             –   At least one time
      ●    A for loop while in C
      ●    A for each (for ... in) style of loop
             –   Order is not garantied
Example: loops.js


· osd12-js.odp
Exceptions

          try       block            catch       (   name   )   block


      throw             expression           ;



 ●   Execution of a block (try)
      ●   All exceptions handled (catch)
      ●   by an exception object (name)
 ●    Any object can be used as exception (throw)
Example: exception.js
· osd12-js.odp
Functions

      function   name       (     name       )


                                   ,



                                   {     statements   }

●    Recursion is allowed
●    Functions can be embedded within function
     (local function)
●    Any object can be returned
· osd12-js.odp
Objects




· osd12-js.odp
Objects
●    Basic object concepts
      ●    Javascript has objects
      ●    Javascript has no classes
●    Mother of all objects: Object
●    Everything is an object
      ●    Booleans, numbers, strings, arrays, functions
●    An object is a set of properties or key/value pairs
●    Values can be all kind of objects

· osd12-js.odp
Objects
●    Create an object: new Object()
●    Indirection: . (dot) or []
●    Remove a property using delete
●    No protection of properties




· osd12-js.odp
Methods
 ●   Values can be (anonymous) functions
      ●    We call them methods
 ●   The keyword this refers to the object in
     methods
 ●   Methods can have internal (aux) functions
Example: objects.js




· osd12-js.odp
Simple constructor
● Define a function
function Graph(title) {
      this.title = title;
}
var g = new Graph('TT');
●    Use capital letters for such objects!



· osd12-js.odp
                                             Example: constructor.js
Prototype
●    Every object has a link to a
                                                                           Figure
     parent                                                     show()

      ●    The property is named
                                                                         prototype
           prototype
●    Differential inheritance                                   position()
                                                                             Box

                                                                area()
      ●    New object is specified by the
           difference from its                                           prototype
           prototype/parent
                                                                          Square
      ●    A long chain of prototypes                           area()
           (delegation)
· osd12-js.odp   Example: differential.js and prototyping.js
                                                               Square.show()
Reflection and Enumeration
●   typeof returns the type of an object (as string)
●   The method hasOwnProperty returns true if object
    (and not parent) has property
●   Operator in can give you all properties
for (name in obj) {
     if (typeof(obj[name]) !== 'function') {
           console.log(name+': '+obj[name]);
     }
}
· osd12-js.odp
Example: graphs
●   A graph is
     ●   A set of nodes and a set of edges (between nodes)
●   Directed Acyclic Graph (DAG)
     ●   Edges have a direction
     ●   And no loops
     ●   Often used for dependency analysis

    Emacs               Cario        libc




                        GTK          glib

    Example: graph.js
· osd12-js.odp
Fluent interfaces
 ●   Common in OOP and JavaScript
      ●    Coined by Martin Fowler
      ●    Chaining method invocations
                  more readable code
      ●    Every method returns reference to object
Examle: fluent.js




· osd12-js.odp
Functions




· osd12-js.odp
Functions
●    Functions are objects
      ●    Functions can be arguments to
           functions
                                                   Object
      ●    And return value
●    Scope is a bit tricky
      ●    Function scope and not block scope     Function

      ●    Inner functions can access outer
           function's variables
                                                function foo



· osd12-js.odp
Anonymous
●    Function without a name
●    Assign as object to variable
●    Useful for callbacks
Example: anonymous.js




· osd12-js.odp
Arguments
●    Listed and named parameters are most
     common
●    Array arguments stores all parameters
      ●    Variable number of arguments
      ●    Order of parameters and array matches




· osd12-js.odp
The meaning of this
●    Implicit parameter this refers to the current
     context
●    Four different invocation patterns
      ●    Method
      ●    Function
      ●    Constructor
      ●    Apply
●    Current context depends on invocation pattern

· osd12-js.odp
Invocation - Method
●    Property in an object
      ●    Key concept in OOP
●    . (dot) is used to refer to function
●    this is set to the object
      ●    Binding of this is done at invocation time
      ●    Access to properties added after adding method




· osd12-js.odp
Invocation - Function
●    Classical procedural programming
      ●    This is set to global scope
      ●    Even for inner functions
●    Work-around is to save a reference to this
      ●    First statements of outer function:
var that;
that = this;


· osd12-js.odp
                                                 Example: inner.js
Invocation - Constructor
●    Functions can be used as constructors
      ●    The new operator create an object
      ●    Function's prototype is used
      ●    this is set to the object
      ●    return will return the object (this)
●    Close to class-based OOP




· osd12-js.odp
Invocation - Apply
●    The Function object has an apply method
      ●    Yes, functions have methods
●    apply has two parameters
      ●    Context – or just simply this
      ●    Arguments – stored in arguments




· osd12-js.odp

                                              Example: apply.js
Closure
●    Functions have access to the context when
     created
●    Context will live as long as the function
●    Useful patterns
      ●    Return a function
      ●    Callbacks
             –   Anonymous function as parameter to function
             –   Has access to context


· osd12-js.odp
                                                           Example: closure.js
Functional programming
 ●   Currying and closures
      ●    Rewrite functions: g x  y= f  x , y 
      ●    Compose functions:         h= f ° g
      ●    Extend Function with a curry method
Examples: highfunc.js




· osd12-js.odp
JavaScript and the browser




· osd12-js.odp
Debugging
●    Firebug is an excellent tool
      ●    Debugger (break point, single stepping)
      ●    HTML and CSS inspector
      ●    Network analysis
●    Cool extensions
      ●    Yslow – give suggesting for better performance
      ●    FireRainbow – syntax highlighting
      ●    FireQuery for jQuery users

· osd12-js.odp
Document Object Model
●    HTML can be a             <table>

     strict file format        <tr><td>X</td><td>Y</td></tr>
                               <tr><td>A</td><td>B</td></tr>
●    Browsers read             </table>
     and parse HTML
                                               table
●    Creates a object
     tree – aka DOM
                                     tr                     tr
●    Viewed in Firebug

                          td              td           td        td

· osd12-js.odp
DOM and JavaScript
●    JavaScript has a runtime library to perform
     DOM manipulations
●    document is the root
●    Give relevant HTML elements an ID
●    onClick property useful
●    Rich API
      ●    getElementById, appendChild,
           removeChild, createElement
Example: dom.html
· osd12-js.odp
JavaScript Object Notation (JSON)
●    Serialization format for JavaScript objects
      ●   Text representation of object
●    Useful for client/server communication
●    Supported by most programming languages

 {               string   :   value   }

                                          [       value   ]
                          ,

                                                      ,

            Object
                                              Array
· osd12-js.odp
JSON
 ●   Browsers have a JSON object
      ●    stringify – create JSON representation
      ●    parse – create an object
Example: json.js




· osd12-js.odp
AJAX
 ●   Asynchronous Javascript And XML
 ●   Main concepts
      ●    Client-side communication with server
      ●    Update DOM – not reload page
      ●    Smaller, well defined backend functions
 ●   XMLHttpRequest object is the core technology
 ●   Web applications look and feel like desktop
     applications
Example: ajax-generic.js, ajax-calc.js, calc.php, calc.html
· osd12-js.odp
Backend
●    Server-side programming in any language
      ●    Perl, Python, Java, C#
●    PHP offers many nice features
      ●    Parsing of query parameters
      ●    JSON
             –   json_decode creates PHP objects
             –   json_encode serializes PHP_objects
             –   They are slow – use only for small objects!
      ●    Access to libraries (MySQL, etc.)
· osd12-js.odp
Third party libraries
●   Open Source libraries try to make cross browser
    development easier
●   Prototype
     ●   Early adaptor – basic functionality
     ●   Scriptacuous (and others) – effects
●   jQuery
     ●   Heavily used today
     ●   Drupal, Microsoft, and others
●   YUI – Yahoo! Library
●   Dojo – avanced but hard to learn
· osd12-js.odp
jQuery
●    DOM manipulations
●    Forms
●    Events
●    AJAX
●    Fluent interface
      ●   $(document.body).css(“background”, 
          “black”)
●    Fancy effects (folding, etc.)
●    Cool stuff (drag-n-drop, etc.)
· osd12-js.odp
DOM
●   $() selects elements based on
    ●   Style class
    ●   Element ID
●   Create and add new elements
    ●   .append – add DOM elements after
    ●   .prepend – add DOM element before
    ●   .html – add raw HTML
●   Delete elements
    ●   .remove – remove elements and it's children
    ●   .empty – remove child nodes
●   Style
    ●   .css – sets using CSS
    ●
· osd12-js.odp
Selectors
  ●    $(…) is the key function in jQuery
  ●    Select DOM elements using CSS selectors
  ●    $(…)returns an array of matching elements
Selector                 Description
'#id'                    Elements' ID attribute
'.class'                 CSS class
'*'                      All elements
'[attr=”value”]'         Attribute matching
'tag'                    Matching HTML tags
                                                  Expresion         Description
                                                  parent > child    Work on subtree
                                                  attr$=”value”     Match at end
        Example: selector.html
                                                  attr^=”value”     Match at start
  · osd12-js.odp
                                                  attr*=”value”     Substring match
Useful methods
●    Each – iterator using anonymous function
●    Append – add an element
●    Remove – delete an element
●    Empty – delete all element
●    Html – get or set raw inner HTML of element
●    Val – get or set the value



· osd12-js.odp
Effects
●   A queue of effects is maintained
    Effects have optional timing parameter
      ●   Integer (ms), slow (600 ms), fast (200 ms)
●   Effects can be stopped and dequeued

Methods                         Effect
show/hide/toogle                visibility
fadeIn/fadeOut/fadeToogle       Visibility - gradually
slideUp/slideDown/slideToogle   Visibility - rolling
delay                           Pause queue execution
· osd12-js.odp
Events
●    Events trigger callback functions
      ●    Anonymous functions are ideal candidates
●    Method bind can add a callback function to
     any element
      ●    click and submit are common events
      ●    $(this) is DOM element as jQuery object
●    Method unbind removes trigger


· osd12-js.odp
Forms
●    Use a selector to find all input elements
●    Method serialize is smarter
      ●    Find input elements
      ●    Creates a URL string for the values
●    Method serializeArray returns an array
      ●    (name, value) pairs
●    val returns value of first element
Example: form.html


· osd12-js.odp
AJAX
 ●   $.ajax is your friend
      ●    $.ajax(url, { })
 ●   It's a remote procedure call/remote method
     invokation
 ●   Three important options
      ●    URL – address of backend function
      ●    data – the parameters
      ●    success – call back function
Example: jquery-ajax.html, calc2.php
· osd12-js.odp
Drag-n-drop
●    Tracking all mouse events
      ●    Mouse down to grab element
      ●    Follow mouse movement – pixel by pixel
      ●    Mouse released to drop element
⇒ Many lines of code
●    JQuery simplifies it
      ●    Define areas (source and destination)
      ●    Use draggable and droppable

· osd12-js.odp
                                          Example: drag-n-drop.html
JavaScript on the server




· osd12-js.odp
Node.js
●   Server-side programming
●   Based on Google's V8 engine
●   Event-driven, non-blocking I/O
●   Used by Google, Microsoft, eBay, LinkedIn,
    Yahoo!
●   Modules for
      ●   TCP listeners, buffers, streams, file I/O, etc.
●   Third party modules
      ●   MySQL, RabbitMQ, ncurses, etc.
· osd12-js.odp
Basic use
●    Installation
      ●    ./configure; make ; make install –
           compiles many C++ files!
      ●    Or binary packages (Windows, OS X, some Linux
           distros)
●    The node or nodejs program is the main
     program
●    Load modules using require
var foo = require('foo')
· osd12-js.odp
Modules
 ●   NODE_PATH sets the path for global modules
 ●   Either low level C++ modules
      ●    This is hard work!
 ●   Or written in JavaScript
      ●    Export is used to export functions
      ●    Require is cached
      ●    And cycles can be detected
Example: diff.js, use-diff.js



· osd12-js.odp
Events
 ●   Objects emit events
      ●    When a connection is opened (server)
      ●    When a file is opened (file system)
 ●   Add an event listener to handle events
      ●    Use addListener or on
      ●    And removeListener when you don't need it
      ●    Just like in the browser
Example: cat.js



· osd12-js.odp
Networking
 ●   Node.js offers various server classes
      ●    net is a general TCP server
      ●    http and https are for web servers
      ●    cluster can spawn multiple listeners
 ●   Clients can be written as well
      ●    dns for name look ups
 ●   UDP is also supported through dgram
Example: node-http.js


· osd12-js.odp
Get on
●    http://ajaxian.com is a great news site for
     Javascript developers
●    Introduktion til Javascript by K. Geisshirt. Libris,
     2010.
●    JavaScript: The Good Parts by D. Crockford.
     O'Reilly, 2008
●    Webmaster in a nutshell by R. Eckstein and S.
     Spainhour. O'Reilly, 2002
●    http://www.wikipedia.org/Javascript
· osd12-js.odp
Summary
●    Javascript supports three programming
     paradigms
      ●    Procedural
      ●    Object-oriented
      ●    Functional
●    Under active development
      ●    Revision of the standard
      ●    New engines
      ●    Many frameworks
· osd12-js.odp

Weitere ähnliche Inhalte

Was ist angesagt?

Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScriptRangana Sampath
 
GR8Conf 2009: What's New in Groovy 1.6? by Guillaume Laforge
GR8Conf 2009: What's New in Groovy 1.6? by Guillaume LaforgeGR8Conf 2009: What's New in Groovy 1.6? by Guillaume Laforge
GR8Conf 2009: What's New in Groovy 1.6? by Guillaume LaforgeGR8Conf
 
JavaScript Object Oriented Programming Cheat Sheet
JavaScript Object Oriented Programming Cheat SheetJavaScript Object Oriented Programming Cheat Sheet
JavaScript Object Oriented Programming Cheat SheetHDR1001
 
A Deeper look into Javascript Basics
A Deeper look into Javascript BasicsA Deeper look into Javascript Basics
A Deeper look into Javascript BasicsMindfire Solutions
 
Scala overview
Scala overviewScala overview
Scala overviewSteve Min
 
Functions and Objects in JavaScript
Functions and Objects in JavaScript Functions and Objects in JavaScript
Functions and Objects in JavaScript Dhananjay Kumar
 
Java 7 Language Enhancement
Java 7 Language EnhancementJava 7 Language Enhancement
Java 7 Language Enhancementmuthusvm
 
An Introduction to JavaScript
An Introduction to JavaScriptAn Introduction to JavaScript
An Introduction to JavaScripttonyh1
 
walkmod: quick start
walkmod: quick startwalkmod: quick start
walkmod: quick startwalkmod
 
BarcelonaJUG2016: walkmod: how to run and design code transformations
BarcelonaJUG2016: walkmod: how to run and design code transformationsBarcelonaJUG2016: walkmod: how to run and design code transformations
BarcelonaJUG2016: walkmod: how to run and design code transformationswalkmod
 
002. Introducere in type script
002. Introducere in type script002. Introducere in type script
002. Introducere in type scriptDmitrii Stoian
 
JavaScript 101
JavaScript 101JavaScript 101
JavaScript 101ygv2000
 
walkmod: An open source tool for coding conventions
walkmod: An open source tool for coding conventionswalkmod: An open source tool for coding conventions
walkmod: An open source tool for coding conventionswalkmod
 
GR8Conf 2009: Practical Groovy DSL by Guillaume Laforge
GR8Conf 2009: Practical Groovy DSL by Guillaume LaforgeGR8Conf 2009: Practical Groovy DSL by Guillaume Laforge
GR8Conf 2009: Practical Groovy DSL by Guillaume LaforgeGR8Conf
 
Typescript tips & tricks
Typescript tips & tricksTypescript tips & tricks
Typescript tips & tricksOri Calvo
 
7 Sins of Java fixed in Kotlin
7 Sins of Java fixed in Kotlin7 Sins of Java fixed in Kotlin
7 Sins of Java fixed in KotlinLuca Guadagnini
 
JavaScript in Object-Oriented Way
JavaScript in Object-Oriented WayJavaScript in Object-Oriented Way
JavaScript in Object-Oriented WayChamnap Chhorn
 

Was ist angesagt? (20)

Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
 
GR8Conf 2009: What's New in Groovy 1.6? by Guillaume Laforge
GR8Conf 2009: What's New in Groovy 1.6? by Guillaume LaforgeGR8Conf 2009: What's New in Groovy 1.6? by Guillaume Laforge
GR8Conf 2009: What's New in Groovy 1.6? by Guillaume Laforge
 
JavaScript Object Oriented Programming Cheat Sheet
JavaScript Object Oriented Programming Cheat SheetJavaScript Object Oriented Programming Cheat Sheet
JavaScript Object Oriented Programming Cheat Sheet
 
A Deeper look into Javascript Basics
A Deeper look into Javascript BasicsA Deeper look into Javascript Basics
A Deeper look into Javascript Basics
 
Scala overview
Scala overviewScala overview
Scala overview
 
Functions and Objects in JavaScript
Functions and Objects in JavaScript Functions and Objects in JavaScript
Functions and Objects in JavaScript
 
Java 7 Language Enhancement
Java 7 Language EnhancementJava 7 Language Enhancement
Java 7 Language Enhancement
 
Introduction to JavaScript Programming
Introduction to JavaScript ProgrammingIntroduction to JavaScript Programming
Introduction to JavaScript Programming
 
An Introduction to JavaScript
An Introduction to JavaScriptAn Introduction to JavaScript
An Introduction to JavaScript
 
PHP Basics
PHP BasicsPHP Basics
PHP Basics
 
walkmod: quick start
walkmod: quick startwalkmod: quick start
walkmod: quick start
 
BarcelonaJUG2016: walkmod: how to run and design code transformations
BarcelonaJUG2016: walkmod: how to run and design code transformationsBarcelonaJUG2016: walkmod: how to run and design code transformations
BarcelonaJUG2016: walkmod: how to run and design code transformations
 
002. Introducere in type script
002. Introducere in type script002. Introducere in type script
002. Introducere in type script
 
JavaScript 101
JavaScript 101JavaScript 101
JavaScript 101
 
walkmod: An open source tool for coding conventions
walkmod: An open source tool for coding conventionswalkmod: An open source tool for coding conventions
walkmod: An open source tool for coding conventions
 
GR8Conf 2009: Practical Groovy DSL by Guillaume Laforge
GR8Conf 2009: Practical Groovy DSL by Guillaume LaforgeGR8Conf 2009: Practical Groovy DSL by Guillaume Laforge
GR8Conf 2009: Practical Groovy DSL by Guillaume Laforge
 
Typescript tips & tricks
Typescript tips & tricksTypescript tips & tricks
Typescript tips & tricks
 
7 Sins of Java fixed in Kotlin
7 Sins of Java fixed in Kotlin7 Sins of Java fixed in Kotlin
7 Sins of Java fixed in Kotlin
 
Ast transformation
Ast transformationAst transformation
Ast transformation
 
JavaScript in Object-Oriented Way
JavaScript in Object-Oriented WayJavaScript in Object-Oriented Way
JavaScript in Object-Oriented Way
 

Ähnlich wie Introduction to JavaScript for Modern Software Development

Node.js Course 1 of 2 - Introduction and first steps
Node.js Course 1 of 2 - Introduction and first stepsNode.js Course 1 of 2 - Introduction and first steps
Node.js Course 1 of 2 - Introduction and first stepsManuel Eusebio de Paz Carmona
 
Dart the Better JavaScript
Dart the Better JavaScriptDart the Better JavaScript
Dart the Better JavaScriptJorg Janke
 
Introduction of Object Oriented JavaScript
Introduction of Object Oriented JavaScriptIntroduction of Object Oriented JavaScript
Introduction of Object Oriented JavaScriptNexThoughts Technologies
 
Kotlin workshop 2018-06-11
Kotlin workshop 2018-06-11Kotlin workshop 2018-06-11
Kotlin workshop 2018-06-11Åsa Pehrsson
 
ooc - OSDC 2010 - Amos Wenger
ooc - OSDC 2010 - Amos Wengerooc - OSDC 2010 - Amos Wenger
ooc - OSDC 2010 - Amos WengerAmos Wenger
 
Java 8 best practices - Stephen Colebourne
Java 8 best practices - Stephen ColebourneJava 8 best practices - Stephen Colebourne
Java 8 best practices - Stephen ColebourneJAXLondon_Conference
 
8 introduction to_java_script
8 introduction to_java_script8 introduction to_java_script
8 introduction to_java_scriptVijay Kalyan
 
HelsinkiJS - Clojurescript for Javascript Developers
HelsinkiJS - Clojurescript for Javascript DevelopersHelsinkiJS - Clojurescript for Javascript Developers
HelsinkiJS - Clojurescript for Javascript DevelopersJuho Teperi
 
javase8bestpractices-151015135520-lva1-app6892
javase8bestpractices-151015135520-lva1-app6892javase8bestpractices-151015135520-lva1-app6892
javase8bestpractices-151015135520-lva1-app6892SRINIVAS C
 
Groovy / comparison with java
Groovy / comparison with javaGroovy / comparison with java
Groovy / comparison with javaLiviu Tudor
 
Reactive Software Systems
Reactive Software SystemsReactive Software Systems
Reactive Software SystemsBehrad Zari
 
An introduction to Object Oriented JavaScript
An introduction to Object Oriented JavaScriptAn introduction to Object Oriented JavaScript
An introduction to Object Oriented JavaScriptTO THE NEW | Technology
 
Basics of Node.js
Basics of Node.jsBasics of Node.js
Basics of Node.jsAlper Unal
 
BCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java DevelopersBCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java DevelopersMiles Sabin
 
An Introduction to Scala for Java Developers
An Introduction to Scala for Java DevelopersAn Introduction to Scala for Java Developers
An Introduction to Scala for Java DevelopersMiles Sabin
 

Ähnlich wie Introduction to JavaScript for Modern Software Development (20)

Node.js Course 1 of 2 - Introduction and first steps
Node.js Course 1 of 2 - Introduction and first stepsNode.js Course 1 of 2 - Introduction and first steps
Node.js Course 1 of 2 - Introduction and first steps
 
Twins: OOP and FP
Twins: OOP and FPTwins: OOP and FP
Twins: OOP and FP
 
Dart the Better JavaScript
Dart the Better JavaScriptDart the Better JavaScript
Dart the Better JavaScript
 
9.4json
9.4json9.4json
9.4json
 
Introduction of Object Oriented JavaScript
Introduction of Object Oriented JavaScriptIntroduction of Object Oriented JavaScript
Introduction of Object Oriented JavaScript
 
Kotlin workshop 2018-06-11
Kotlin workshop 2018-06-11Kotlin workshop 2018-06-11
Kotlin workshop 2018-06-11
 
Object Oriented Javascript
Object Oriented JavascriptObject Oriented Javascript
Object Oriented Javascript
 
ooc - OSDC 2010 - Amos Wenger
ooc - OSDC 2010 - Amos Wengerooc - OSDC 2010 - Amos Wenger
ooc - OSDC 2010 - Amos Wenger
 
Java 8 best practices - Stephen Colebourne
Java 8 best practices - Stephen ColebourneJava 8 best practices - Stephen Colebourne
Java 8 best practices - Stephen Colebourne
 
8 introduction to_java_script
8 introduction to_java_script8 introduction to_java_script
8 introduction to_java_script
 
HelsinkiJS - Clojurescript for Javascript Developers
HelsinkiJS - Clojurescript for Javascript DevelopersHelsinkiJS - Clojurescript for Javascript Developers
HelsinkiJS - Clojurescript for Javascript Developers
 
Java SE 8 best practices
Java SE 8 best practicesJava SE 8 best practices
Java SE 8 best practices
 
javase8bestpractices-151015135520-lva1-app6892
javase8bestpractices-151015135520-lva1-app6892javase8bestpractices-151015135520-lva1-app6892
javase8bestpractices-151015135520-lva1-app6892
 
Groovy / comparison with java
Groovy / comparison with javaGroovy / comparison with java
Groovy / comparison with java
 
Reactive Software Systems
Reactive Software SystemsReactive Software Systems
Reactive Software Systems
 
Plpgsql russia-pgconf
Plpgsql russia-pgconfPlpgsql russia-pgconf
Plpgsql russia-pgconf
 
An introduction to Object Oriented JavaScript
An introduction to Object Oriented JavaScriptAn introduction to Object Oriented JavaScript
An introduction to Object Oriented JavaScript
 
Basics of Node.js
Basics of Node.jsBasics of Node.js
Basics of Node.js
 
BCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java DevelopersBCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java Developers
 
An Introduction to Scala for Java Developers
An Introduction to Scala for Java DevelopersAn Introduction to Scala for Java Developers
An Introduction to Scala for Java Developers
 

Mehr von Kenneth Geisshirt

Building parsers in JavaScript
Building parsers in JavaScriptBuilding parsers in JavaScript
Building parsers in JavaScriptKenneth Geisshirt
 
Building mobile apps with Realm for React Native
Building mobile apps with Realm for React NativeBuilding mobile apps with Realm for React Native
Building mobile apps with Realm for React NativeKenneth Geisshirt
 
Tales from the dark side: developing SDKs at scale
Tales from the dark side: developing SDKs at scaleTales from the dark side: developing SDKs at scale
Tales from the dark side: developing SDKs at scaleKenneth Geisshirt
 
Unleash your inner console cowboy
Unleash your inner console cowboyUnleash your inner console cowboy
Unleash your inner console cowboyKenneth Geisshirt
 
Tips and tricks for building high performance android apps using native code
Tips and tricks for building high performance android apps using native codeTips and tricks for building high performance android apps using native code
Tips and tricks for building high performance android apps using native codeKenneth Geisshirt
 
Is the database a solved problem?
Is the database a solved problem?Is the database a solved problem?
Is the database a solved problem?Kenneth Geisshirt
 
Unleash your inner console cowboy
Unleash your inner console cowboyUnleash your inner console cowboy
Unleash your inner console cowboyKenneth Geisshirt
 
Building High Performance Android Applications in Java and C++
Building High Performance Android Applications in Java and C++Building High Performance Android Applications in Java and C++
Building High Performance Android Applications in Java and C++Kenneth Geisshirt
 
Unleash your inner console cowboy
Unleash your inner console cowboyUnleash your inner console cowboy
Unleash your inner console cowboyKenneth Geisshirt
 
Naturvidenskabsfestival 2012
Naturvidenskabsfestival 2012Naturvidenskabsfestival 2012
Naturvidenskabsfestival 2012Kenneth Geisshirt
 
Hadoop - the data scientist's toolbox
Hadoop - the data scientist's toolboxHadoop - the data scientist's toolbox
Hadoop - the data scientist's toolboxKenneth Geisshirt
 
JavaScript/Emacs integration
JavaScript/Emacs integrationJavaScript/Emacs integration
JavaScript/Emacs integrationKenneth Geisshirt
 

Mehr von Kenneth Geisshirt (19)

Building parsers in JavaScript
Building parsers in JavaScriptBuilding parsers in JavaScript
Building parsers in JavaScript
 
Open Source in Real Life
Open Source in Real LifeOpen Source in Real Life
Open Source in Real Life
 
Building mobile apps with Realm for React Native
Building mobile apps with Realm for React NativeBuilding mobile apps with Realm for React Native
Building mobile apps with Realm for React Native
 
micro:bit and JavaScript
micro:bit and JavaScriptmicro:bit and JavaScript
micro:bit and JavaScript
 
Tales from the dark side: developing SDKs at scale
Tales from the dark side: developing SDKs at scaleTales from the dark side: developing SDKs at scale
Tales from the dark side: developing SDKs at scale
 
Android things
Android thingsAndroid things
Android things
 
Node.js extensions in C++
Node.js extensions in C++Node.js extensions in C++
Node.js extensions in C++
 
Unleash your inner console cowboy
Unleash your inner console cowboyUnleash your inner console cowboy
Unleash your inner console cowboy
 
Tips and tricks for building high performance android apps using native code
Tips and tricks for building high performance android apps using native codeTips and tricks for building high performance android apps using native code
Tips and tricks for building high performance android apps using native code
 
Is the database a solved problem?
Is the database a solved problem?Is the database a solved problem?
Is the database a solved problem?
 
Unleash your inner console cowboy
Unleash your inner console cowboyUnleash your inner console cowboy
Unleash your inner console cowboy
 
Extending Node.js using C++
Extending Node.js using C++Extending Node.js using C++
Extending Node.js using C++
 
Building High Performance Android Applications in Java and C++
Building High Performance Android Applications in Java and C++Building High Performance Android Applications in Java and C++
Building High Performance Android Applications in Java and C++
 
Sociale netværk
Sociale netværkSociale netværk
Sociale netværk
 
Unleash your inner console cowboy
Unleash your inner console cowboyUnleash your inner console cowboy
Unleash your inner console cowboy
 
Naturvidenskabsfestival 2012
Naturvidenskabsfestival 2012Naturvidenskabsfestival 2012
Naturvidenskabsfestival 2012
 
Hadoop - the data scientist's toolbox
Hadoop - the data scientist's toolboxHadoop - the data scientist's toolbox
Hadoop - the data scientist's toolbox
 
JavaScript/Emacs integration
JavaScript/Emacs integrationJavaScript/Emacs integration
JavaScript/Emacs integration
 
Kendthed og vigtighed
Kendthed og vigtighedKendthed og vigtighed
Kendthed og vigtighed
 

Kürzlich hochgeladen

Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesZilliz
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 

Kürzlich hochgeladen (20)

Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector Databases
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 

Introduction to JavaScript for Modern Software Development

  • 1. Introduction to JavaScript For Modern Software Development Kenneth Geisshirt http://kenneth.geisshirt.dk/ · osd12-js.odp
  • 2. Agenda – before lunch ● History and standard ● Implementations ● Tools ● Syntax ● Procedural programming ● Object-orientation ● Functions as first-class object ● Fluent interfaces · osd12-js.odp
  • 3. Tools ● Syntax highlighting in most editors ● JSLint is a great code checker ● http://jslint.com/ ● Easy to run using Rhino and integrate with Emacs ● Firebug has a nice Javascript debugger ● http://getfirebug.com/ ● Web developers: use a framework: ● Jquery - http://jquery.com/ ● YUI - http://developer.yahoo.com/yui/ ● Prototype - http://prototypejs.org/ Dojo - http://www.dojotoolkit.org/ ● ● Underscore - http://documentcloud.github.com/underscore/ · osd12-js.odp
  • 4. Agenda – after lunch ● JavaScript and the browser ● Interaction with DOM ● JSON ● AJAX ● Moderne web programming ● Jquery ● Back-end programming ● Node.js · osd12-js.odp
  • 5. Features ● Dynamic ● Extending and modifying a running program ● Weakly typed ● Implicit type conversion ● Implicit declared variables ● Prototype-based objects ● Objects but no classes ● Functions as first-class objects ● A Function is just an object · osd12-js.odp
  • 6. History and standard ● Designed by Brendan Eich (Netscape) in 1995 ● Netscape Communicator 2.0b3 (December 1995) ● Internet Explorer 3.0 (August 1996) ● JavaScript is a Oracle trademark ● Standardized by ECMA ● Official name ECMAScript ● ECMA-262/ISO-16262 (1997) ● Revision 5.1 is latest revision (June 2011) · osd12-js.odp
  • 7. Implementations ● Closed source ● JScript (Microsoft) ● Futhark (Opera) ● Open Source ● SpiderMonkey (Mozilla, written in C) ● Rhino (Mozilla, written in Java) ● QtScript (Nokia Troll Tech) ● JavaScriptCore (Apple) ● V8 (Google) · osd12-js.odp
  • 8. Future implementations ● Just-In-Time (JIT) is becoming popular ● V8 is doing it already ● TraceMonkey and JägerMonkey (Mozilla) ● SquirrelFish (Apple) ● Carakan (Opera) ● Tamparin (Adobe and Mozilla) ● Size does matter (smaller is better) ● Transformation and compression of code ● Google Closure · osd12-js.odp
  • 10. Syntax – comments and lines ● Just like C ● The rest of the line: // ● Multi-line: /* */ ● // is recommeded by Javascript developers ● Statement separator is ; (semicolon) ● Statements can span multiple lines ● White spaces: space and tab ● Case sensitive · osd12-js.odp
  • 11. Syntax – literals ● Booleans ● Examples: true, false ● Other false values: null, NaN, '', 0, undefined ● Numbers ● Integers – Examples: 42, 101010 ● Real numbers – Examples: 3.1415926535, 6.022e23, 6.626e-34 ● Strings ● Examples: “Hello”, 'world', “Don't panic” · osd12-js.odp
  • 12. Syntax - names ● Begin with a letter Reserved words ● can be followed by abstract, boolean, break, byte, letters, digits and case, catch, char, const, continue, underscores (_) debugger, default, delete, do, double, else, enum, export, ● Many extends, false, final, float, for, implementations function, goto, if, implements, import, in, instanceof, int, allow dollar and interface, long, native, new, null, underscore as first package, private, protected, character public, return, short, static, super, switch, synchronized, this, throw, throws, transient, true, try, typeof, var, volatile, void, while, with · osd12-js.odp
  • 13. Syntax - expression literal name ( expression ) expression operator expression prefix expression function call “hello “+”world”, f(42), 1.0/(x+y), -3.14, 5>7 Example: expr.js · osd12-js.odp
  • 14. Syntax – expression ● typeof(·) returns type of the argument as string ● undefined, boolean, number, string, object, function ● Equality: === and !== ● Inequality: <, >, >=, <= ● Logical: && (and), || (or), ! (not) ● Arithmetic: +, -, *, /, % ● String concatenation: + ● += and -= can be used (but not recommended) Example: opers.js · osd12-js.odp
  • 15. == vs === ● == compares values ● === compares values and types ● Similar for != and !== ● Recommendation: use === and !== Example: equal.js · osd12-js.odp
  • 16. Arrays ● Two ways to create an array ● Recommended: a = [2.7182, 3.1415] ● a = new Array() ● Zero based index ● Elements do not have to be of the same type ● Indirection by [] ● Property length is the number of elements Example: array.js · osd12-js.odp
  • 18. Procedural programming var name = expression , ● Declare variables ● Only global name space ● No late declarations – Visible in all function ● Interpreter deduces type at runtime · osd12-js.odp
  • 19. Blocks { statements } ● Block is similar to blocks in C ● But they do not declare a scope ● Variables are visible before and after the block ● Advice: declare all variables in the top of functions · osd12-js.odp
  • 20. Branches if ( expression ) block else block ● Falsy values for an expression: ● false, null, undefined, '', 0, NaN ● All other values are true Example: if.js · osd12-js.odp
  • 21. Other branches ● The switch construct is similar to C ● Case expressions can be variable ● And can be a number or a string ● Each case must be terminated by break switch (c) { case 'A': break; } Example: switch.js · osd12-js.odp
  • 22. Loops ● Four loops constructions exist ● Execute while an expression is true – Zero or more times ● do while an expression is true – At least one time ● A for loop while in C ● A for each (for ... in) style of loop – Order is not garantied Example: loops.js · osd12-js.odp
  • 23. Exceptions try block catch ( name ) block throw expression ; ● Execution of a block (try) ● All exceptions handled (catch) ● by an exception object (name) ● Any object can be used as exception (throw) Example: exception.js · osd12-js.odp
  • 24. Functions function name ( name ) , { statements } ● Recursion is allowed ● Functions can be embedded within function (local function) ● Any object can be returned · osd12-js.odp
  • 26. Objects ● Basic object concepts ● Javascript has objects ● Javascript has no classes ● Mother of all objects: Object ● Everything is an object ● Booleans, numbers, strings, arrays, functions ● An object is a set of properties or key/value pairs ● Values can be all kind of objects · osd12-js.odp
  • 27. Objects ● Create an object: new Object() ● Indirection: . (dot) or [] ● Remove a property using delete ● No protection of properties · osd12-js.odp
  • 28. Methods ● Values can be (anonymous) functions ● We call them methods ● The keyword this refers to the object in methods ● Methods can have internal (aux) functions Example: objects.js · osd12-js.odp
  • 29. Simple constructor ● Define a function function Graph(title) { this.title = title; } var g = new Graph('TT'); ● Use capital letters for such objects! · osd12-js.odp Example: constructor.js
  • 30. Prototype ● Every object has a link to a Figure parent show() ● The property is named prototype prototype ● Differential inheritance position() Box area() ● New object is specified by the difference from its prototype prototype/parent Square ● A long chain of prototypes area() (delegation) · osd12-js.odp Example: differential.js and prototyping.js Square.show()
  • 31. Reflection and Enumeration ● typeof returns the type of an object (as string) ● The method hasOwnProperty returns true if object (and not parent) has property ● Operator in can give you all properties for (name in obj) { if (typeof(obj[name]) !== 'function') { console.log(name+': '+obj[name]); } } · osd12-js.odp
  • 32. Example: graphs ● A graph is ● A set of nodes and a set of edges (between nodes) ● Directed Acyclic Graph (DAG) ● Edges have a direction ● And no loops ● Often used for dependency analysis Emacs Cario libc GTK glib Example: graph.js · osd12-js.odp
  • 33. Fluent interfaces ● Common in OOP and JavaScript ● Coined by Martin Fowler ● Chaining method invocations  more readable code ● Every method returns reference to object Examle: fluent.js · osd12-js.odp
  • 35. Functions ● Functions are objects ● Functions can be arguments to functions Object ● And return value ● Scope is a bit tricky ● Function scope and not block scope Function ● Inner functions can access outer function's variables function foo · osd12-js.odp
  • 36. Anonymous ● Function without a name ● Assign as object to variable ● Useful for callbacks Example: anonymous.js · osd12-js.odp
  • 37. Arguments ● Listed and named parameters are most common ● Array arguments stores all parameters ● Variable number of arguments ● Order of parameters and array matches · osd12-js.odp
  • 38. The meaning of this ● Implicit parameter this refers to the current context ● Four different invocation patterns ● Method ● Function ● Constructor ● Apply ● Current context depends on invocation pattern · osd12-js.odp
  • 39. Invocation - Method ● Property in an object ● Key concept in OOP ● . (dot) is used to refer to function ● this is set to the object ● Binding of this is done at invocation time ● Access to properties added after adding method · osd12-js.odp
  • 40. Invocation - Function ● Classical procedural programming ● This is set to global scope ● Even for inner functions ● Work-around is to save a reference to this ● First statements of outer function: var that; that = this; · osd12-js.odp Example: inner.js
  • 41. Invocation - Constructor ● Functions can be used as constructors ● The new operator create an object ● Function's prototype is used ● this is set to the object ● return will return the object (this) ● Close to class-based OOP · osd12-js.odp
  • 42. Invocation - Apply ● The Function object has an apply method ● Yes, functions have methods ● apply has two parameters ● Context – or just simply this ● Arguments – stored in arguments · osd12-js.odp Example: apply.js
  • 43. Closure ● Functions have access to the context when created ● Context will live as long as the function ● Useful patterns ● Return a function ● Callbacks – Anonymous function as parameter to function – Has access to context · osd12-js.odp Example: closure.js
  • 44. Functional programming ● Currying and closures ● Rewrite functions: g x  y= f  x , y  ● Compose functions: h= f ° g ● Extend Function with a curry method Examples: highfunc.js · osd12-js.odp
  • 45. JavaScript and the browser · osd12-js.odp
  • 46. Debugging ● Firebug is an excellent tool ● Debugger (break point, single stepping) ● HTML and CSS inspector ● Network analysis ● Cool extensions ● Yslow – give suggesting for better performance ● FireRainbow – syntax highlighting ● FireQuery for jQuery users · osd12-js.odp
  • 47. Document Object Model ● HTML can be a <table> strict file format <tr><td>X</td><td>Y</td></tr> <tr><td>A</td><td>B</td></tr> ● Browsers read </table> and parse HTML table ● Creates a object tree – aka DOM tr tr ● Viewed in Firebug td td td td · osd12-js.odp
  • 48. DOM and JavaScript ● JavaScript has a runtime library to perform DOM manipulations ● document is the root ● Give relevant HTML elements an ID ● onClick property useful ● Rich API ● getElementById, appendChild, removeChild, createElement Example: dom.html · osd12-js.odp
  • 49. JavaScript Object Notation (JSON) ● Serialization format for JavaScript objects ● Text representation of object ● Useful for client/server communication ● Supported by most programming languages { string : value } [ value ] , , Object Array · osd12-js.odp
  • 50. JSON ● Browsers have a JSON object ● stringify – create JSON representation ● parse – create an object Example: json.js · osd12-js.odp
  • 51. AJAX ● Asynchronous Javascript And XML ● Main concepts ● Client-side communication with server ● Update DOM – not reload page ● Smaller, well defined backend functions ● XMLHttpRequest object is the core technology ● Web applications look and feel like desktop applications Example: ajax-generic.js, ajax-calc.js, calc.php, calc.html · osd12-js.odp
  • 52. Backend ● Server-side programming in any language ● Perl, Python, Java, C# ● PHP offers many nice features ● Parsing of query parameters ● JSON – json_decode creates PHP objects – json_encode serializes PHP_objects – They are slow – use only for small objects! ● Access to libraries (MySQL, etc.) · osd12-js.odp
  • 53. Third party libraries ● Open Source libraries try to make cross browser development easier ● Prototype ● Early adaptor – basic functionality ● Scriptacuous (and others) – effects ● jQuery ● Heavily used today ● Drupal, Microsoft, and others ● YUI – Yahoo! Library ● Dojo – avanced but hard to learn · osd12-js.odp
  • 54. jQuery ● DOM manipulations ● Forms ● Events ● AJAX ● Fluent interface ● $(document.body).css(“background”,  “black”) ● Fancy effects (folding, etc.) ● Cool stuff (drag-n-drop, etc.) · osd12-js.odp
  • 55. DOM ● $() selects elements based on ● Style class ● Element ID ● Create and add new elements ● .append – add DOM elements after ● .prepend – add DOM element before ● .html – add raw HTML ● Delete elements ● .remove – remove elements and it's children ● .empty – remove child nodes ● Style ● .css – sets using CSS ● · osd12-js.odp
  • 56. Selectors ● $(…) is the key function in jQuery ● Select DOM elements using CSS selectors ● $(…)returns an array of matching elements Selector Description '#id' Elements' ID attribute '.class' CSS class '*' All elements '[attr=”value”]' Attribute matching 'tag' Matching HTML tags Expresion Description parent > child Work on subtree attr$=”value” Match at end Example: selector.html attr^=”value” Match at start · osd12-js.odp attr*=”value” Substring match
  • 57. Useful methods ● Each – iterator using anonymous function ● Append – add an element ● Remove – delete an element ● Empty – delete all element ● Html – get or set raw inner HTML of element ● Val – get or set the value · osd12-js.odp
  • 58. Effects ● A queue of effects is maintained Effects have optional timing parameter ● Integer (ms), slow (600 ms), fast (200 ms) ● Effects can be stopped and dequeued Methods Effect show/hide/toogle visibility fadeIn/fadeOut/fadeToogle Visibility - gradually slideUp/slideDown/slideToogle Visibility - rolling delay Pause queue execution · osd12-js.odp
  • 59. Events ● Events trigger callback functions ● Anonymous functions are ideal candidates ● Method bind can add a callback function to any element ● click and submit are common events ● $(this) is DOM element as jQuery object ● Method unbind removes trigger · osd12-js.odp
  • 60. Forms ● Use a selector to find all input elements ● Method serialize is smarter ● Find input elements ● Creates a URL string for the values ● Method serializeArray returns an array ● (name, value) pairs ● val returns value of first element Example: form.html · osd12-js.odp
  • 61. AJAX ● $.ajax is your friend ● $.ajax(url, { }) ● It's a remote procedure call/remote method invokation ● Three important options ● URL – address of backend function ● data – the parameters ● success – call back function Example: jquery-ajax.html, calc2.php · osd12-js.odp
  • 62. Drag-n-drop ● Tracking all mouse events ● Mouse down to grab element ● Follow mouse movement – pixel by pixel ● Mouse released to drop element ⇒ Many lines of code ● JQuery simplifies it ● Define areas (source and destination) ● Use draggable and droppable · osd12-js.odp Example: drag-n-drop.html
  • 63. JavaScript on the server · osd12-js.odp
  • 64. Node.js ● Server-side programming ● Based on Google's V8 engine ● Event-driven, non-blocking I/O ● Used by Google, Microsoft, eBay, LinkedIn, Yahoo! ● Modules for ● TCP listeners, buffers, streams, file I/O, etc. ● Third party modules ● MySQL, RabbitMQ, ncurses, etc. · osd12-js.odp
  • 65. Basic use ● Installation ● ./configure; make ; make install – compiles many C++ files! ● Or binary packages (Windows, OS X, some Linux distros) ● The node or nodejs program is the main program ● Load modules using require var foo = require('foo') · osd12-js.odp
  • 66. Modules ● NODE_PATH sets the path for global modules ● Either low level C++ modules ● This is hard work! ● Or written in JavaScript ● Export is used to export functions ● Require is cached ● And cycles can be detected Example: diff.js, use-diff.js · osd12-js.odp
  • 67. Events ● Objects emit events ● When a connection is opened (server) ● When a file is opened (file system) ● Add an event listener to handle events ● Use addListener or on ● And removeListener when you don't need it ● Just like in the browser Example: cat.js · osd12-js.odp
  • 68. Networking ● Node.js offers various server classes ● net is a general TCP server ● http and https are for web servers ● cluster can spawn multiple listeners ● Clients can be written as well ● dns for name look ups ● UDP is also supported through dgram Example: node-http.js · osd12-js.odp
  • 69. Get on ● http://ajaxian.com is a great news site for Javascript developers ● Introduktion til Javascript by K. Geisshirt. Libris, 2010. ● JavaScript: The Good Parts by D. Crockford. O'Reilly, 2008 ● Webmaster in a nutshell by R. Eckstein and S. Spainhour. O'Reilly, 2002 ● http://www.wikipedia.org/Javascript · osd12-js.odp
  • 70. Summary ● Javascript supports three programming paradigms ● Procedural ● Object-oriented ● Functional ● Under active development ● Revision of the standard ● New engines ● Many frameworks · osd12-js.odp