Javascript
                        the Programming Language of the Web
                                   Anders Janmyr
  ...
Ugly
     Javascript




Thursday, May 6, 2010
Syntax

Thursday, May 6, 2010
Values



Thursday, May 6, 2010
Number

                    • 64-bit floating point Double
                    • 0.1 + 0.2 = 0.30000000000000004	

        ...
Strings


                    • Immutable
                    • ‘a string’ == “a string”


Thursday, May 6, 2010
Booleans

                    • true
                    • false
                    • Boolean()
                     • re...
null




Thursday, May 6, 2010
Undefined

                    • Not even null
                    • Default value
                       • Parameters
    ...
Object


                    • Everything else
                    • Including functions


Thursday, May 6, 2010
Statements



Thursday, May 6, 2010
var

                    • Declares a variable
                    • If you forget it will be defined globally!
           ...
Conditionals
                    • If
                    • Switch - Case
                if (unit == 'Litre')
           ...
Loops
                  • while
                  • do - while
                  • for(var i; i<42; i++)
                 ...
Exceptions
                try {
                    setSelected(target);
                    f();
                } catch...
Disruptive

                    • return [value]
                    • break [label]
                    • continue [label...
Literals
                        number                         1.234
                        string            ‘anders’, ...
typeof
                        type         typeof

                        object       'object'

                       ...
Equality


                    • 5 == “5” // true
                    • 5 === “5” // false


Thursday, May 6, 2010
Beautiful
        Javascript




Thursday, May 6, 2010
Object


                        Hashtable


Thursday, May 6, 2010
Object


                        Dynamic


Thursday, May 6, 2010
Object


                        Prototypical


Thursday, May 6, 2010
Object Literal


                        var empty_object = {};




Thursday, May 6, 2010
var kjell = {
                            name: "Kjell",
                            "kind": "Malayan"
                   ...
var kjell = {
                            name: "Kjell",
                            "kind": "Malayan"
                   ...
Retrieval
                   kjell.name    // “Kjell”
                   kjell["name"] // “Kjell”

                   // D...
Retrieving non-existent
                        properties
                 kjell.firstname // undefined
                 ...
Setting non-existent
                             properties
                        kjell.firstname = 'Sven';
           ...
Prototypical Inheritance
                  using Object.create
                        var rudolph =
                     ...
Prototypical Inheritance
                                  name    Kjell
                                  kind   Malayan
...
rudolph.name = 'Rudolph';

                        rudolph.name // “Rudolph”
                        kjell.name   // “Kjel...
rudolph.kind   // ‘Malayan’


                        kjell.kind = 'Baird';

                        rudolph.kind   // ‘Ba...
delete rudolph.name

                        rudolph.name // ‘Kjell’




Thursday, May 6, 2010
Prototypical Inheritance
                          new Constructor();


                        Returns a new object with ...
Prototypical Inheritance
              Object.create = function(o) {
                  function F() {}
                  F...
Prototypical Inheritance
                                  name     kjell
                                  kind   Malayan...
Arrays

                    • Array inherits from object
                    • Indexes are converted to strings
          ...
Array Literals

                    • []
                    • names = [ ‘Rudolph’, ‘Kjell’, ‘Torsten’]
                  ...
Array Methods
                    • concat
                    • join
                    • pop
                    • push...
JSON
          {
                    "version": "1.0",
                    "markets": [
                        { "name": ...
Function

                        First class
                          object


Thursday, May 6, 2010
Function


                         lambda
                        function() {};




Thursday, May 6, 2010
Function Statement
                        function foo() {}

                        expands to

                        ...
Functions

                        Can be defined inside other functions!




Thursday, May 6, 2010
residualValues: function(cur) {
       var self = this;
       return function() {
         return [1,2,3,4,5].map(functio...
Methods

                        functions stored in objects




Thursday, May 6, 2010
Built-in Prototypes
                    • Object.prototype
                    • Array.prototype
                    • Fun...
Array.prototype.contains = function(element)
  {
      for (var i = 0; i < this.length; i++) {
          if (this[i] == el...
Function.prototype.method =
                          function(name, func) {
                            this.prototype[na...
String.method(‘trim’, function() {
            return this.replace(/^s+|s+$/g, ‘’);
          }




          “ tapir “.tr...
Scope

               The function is the scope of the
                          variables




Thursday, May 6, 2010
Invocation Forms
                    • Function form
                     • sleep(10)
                    • Method form
  ...
this
                                Invocation      this
            this is an extra       Form
            parameter th...
arguments

                    • A special array like, DYNAMIC, parameter

                    • All the arguments of the ...
function sum() {
                 var i,
                     n = arguments.length,
                     total = 0;
      ...
Dynamic Compilation

                    • eval
                     • Evaluates a string and returns the result.
        ...
Global
   Variables




Thursday, May 6, 2010
The global Object

                    • Container for all variables
                    • On browsers window == global
  ...
Good
                        Practices




Thursday, May 6, 2010
Cascade
                         setFirst: function(name) {
                           this.first = name;
                ...
Modules

                        var MyNamespace = {};


                        var MyNS = MyNS || {};




Thursday, May ...
Encapsulation
                        var Esperanto = Esperanto || {};

                        Esperanto.Lab = function()...
Local Functions
                 costData: function(current) {
                     var data = {};
                     fu...
self = this
      attachFormListener: function(form, object) {
          var self = this;
          function populator(eve...
Mixins

                Object.mixin = function(destination, source) {
                   for (property in source)
       ...
Aspects

                        around: function(obj, fname, advice) {
                             var oldFunc = obj[fna...
Lab


    http://10.48.44.155/~andersjanmyr/




Thursday, May 6, 2010
Thank you!
                           Anders Janmyr
                          http://anders.janmyr.com
                   ...
Javascript the Language of the Web
Javascript the Language of the Web
Javascript the Language of the Web
Javascript the Language of the Web
Javascript the Language of the Web
Javascript the Language of the Web
Javascript the Language of the Web
Javascript the Language of the Web
Javascript the Language of the Web
Javascript the Language of the Web
Javascript the Language of the Web
Javascript the Language of the Web
Javascript the Language of the Web
Javascript the Language of the Web
Javascript the Language of the Web
Javascript the Language of the Web
Upcoming SlideShare
Loading in …5
×

Javascript the Language of the Web

1,638 views

Published on

Crash introduction to Javascript

Published in: Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
1,638
On SlideShare
0
From Embeds
0
Number of Embeds
11
Actions
Shares
0
Downloads
44
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Javascript the Language of the Web

  1. 1. Javascript the Programming Language of the Web Anders Janmyr http://anders.janmyr.com anders.janmyr@jayway.com     Copyright is held by the author/owner(s).     OOPSLA'09, October 25–29, 2009, Orlando, FL, USA.     ACM 09/10. Thursday, May 6, 2010
  2. 2. Ugly Javascript Thursday, May 6, 2010
  3. 3. Syntax Thursday, May 6, 2010
  4. 4. Values Thursday, May 6, 2010
  5. 5. Number • 64-bit floating point Double • 0.1 + 0.2 = 0.30000000000000004 • NaN Thursday, May 6, 2010
  6. 6. Strings • Immutable • ‘a string’ == “a string” Thursday, May 6, 2010
  7. 7. Booleans • true • false • Boolean() • returns false for falsy values • false, null, undefined, "", 0, NaN Thursday, May 6, 2010
  8. 8. null Thursday, May 6, 2010
  9. 9. Undefined • Not even null • Default value • Parameters • Arguments • Non-existent members Thursday, May 6, 2010
  10. 10. Object • Everything else • Including functions Thursday, May 6, 2010
  11. 11. Statements Thursday, May 6, 2010
  12. 12. var • Declares a variable • If you forget it will be defined globally! • Scope of variable is the function Thursday, May 6, 2010
  13. 13. Conditionals • If • Switch - Case if (unit == 'Litre') return value; else return this.withTwoDecimals(value / 3.7854); Thursday, May 6, 2010
  14. 14. Loops • while • do - while • for(var i; i<42; i++) • for (key in object) for (var key in market) { current.market[key] = gui.convert(market[key]); } Thursday, May 6, 2010
  15. 15. Exceptions try { setSelected(target); f(); } catch (err) { console.log(err); } throw(anyObject) Thursday, May 6, 2010
  16. 16. Disruptive • return [value] • break [label] • continue [label] • throw object Thursday, May 6, 2010
  17. 17. Literals number 1.234 string ‘anders’, “janmyr” object {} array [] function function() {} regexp /^anders$/ Thursday, May 6, 2010
  18. 18. typeof type typeof object 'object' function 'function' array 'object' number 'number' string 'string' boolean 'boolean' null 'object' undefined 'undefined' Thursday, May 6, 2010
  19. 19. Equality • 5 == “5” // true • 5 === “5” // false Thursday, May 6, 2010
  20. 20. Beautiful Javascript Thursday, May 6, 2010
  21. 21. Object Hashtable Thursday, May 6, 2010
  22. 22. Object Dynamic Thursday, May 6, 2010
  23. 23. Object Prototypical Thursday, May 6, 2010
  24. 24. Object Literal var empty_object = {}; Thursday, May 6, 2010
  25. 25. var kjell = { name: "Kjell", "kind": "Malayan" }; Thursday, May 6, 2010
  26. 26. var kjell = { name: "Kjell", "kind": "Malayan" address: { country: "Denmark" } }; Thursday, May 6, 2010
  27. 27. Retrieval kjell.name // “Kjell” kjell["name"] // “Kjell” // Denmark kjell.address.country kjell['address']["country"] Thursday, May 6, 2010
  28. 28. Retrieving non-existent properties kjell.firstname // undefined kjell["NAME"] // undefined kjell.home.country // Error Thursday, May 6, 2010
  29. 29. Setting non-existent properties kjell.firstname = 'Sven'; kjell["NAME"] = 'SVEN'; kjell.firstname // 'Sven' Thursday, May 6, 2010
  30. 30. Prototypical Inheritance using Object.create var rudolph = Object.create(kjell); rudolph.name // “Kjell” Thursday, May 6, 2010
  31. 31. Prototypical Inheritance name Kjell kind Malayan name Rudolph prototype Thursday, May 6, 2010
  32. 32. rudolph.name = 'Rudolph'; rudolph.name // “Rudolph” kjell.name // “Kjell” rudolph.kind // ‘Malayan’ Thursday, May 6, 2010
  33. 33. rudolph.kind // ‘Malayan’ kjell.kind = 'Baird'; rudolph.kind // ‘Baird’ Thursday, May 6, 2010
  34. 34. delete rudolph.name rudolph.name // ‘Kjell’ Thursday, May 6, 2010
  35. 35. Prototypical Inheritance new Constructor(); Returns a new object with a link to Constructor.prototype Thursday, May 6, 2010
  36. 36. Prototypical Inheritance Object.create = function(o) { function F() {} F.prototype = o; return new F(); } Thursday, May 6, 2010
  37. 37. Prototypical Inheritance name kjell kind Malayan... name rudolph prototype Thursday, May 6, 2010
  38. 38. Arrays • Array inherits from object • Indexes are converted to strings • Magic length property • Always one larger than the highest int property Thursday, May 6, 2010
  39. 39. Array Literals • [] • names = [ ‘Rudolph’, ‘Kjell’, ‘Torsten’] • typeof value == ‘object’ • value.constructor === Array Thursday, May 6, 2010
  40. 40. Array Methods • concat • join • pop • push • slice • sort • splice Thursday, May 6, 2010
  41. 41. JSON { "version": "1.0", "markets": [ { "name": "Europe", "currency": "EUR"}, { "name": "North America", "currency": "USD"}, { "name": "Other", "currency": "USD"} ], "serviceTypes": ["Maintenence", "WearingPart"], "valueTypes": ["Market value", "Trade in value"] } Thursday, May 6, 2010
  42. 42. Function First class object Thursday, May 6, 2010
  43. 43. Function lambda function() {}; Thursday, May 6, 2010
  44. 44. Function Statement function foo() {} expands to var foo = function foo() {}; Thursday, May 6, 2010
  45. 45. Functions Can be defined inside other functions! Thursday, May 6, 2010
  46. 46. residualValues: function(cur) { var self = this; return function() { return [1,2,3,4,5].map(function(age) { return { years: age, value: self.tradePercent(cur, age) }; }); } } Thursday, May 6, 2010
  47. 47. Methods functions stored in objects Thursday, May 6, 2010
  48. 48. Built-in Prototypes • Object.prototype • Array.prototype • Function.prototype • Number.prototype • String.prototype • Boolean.prototype Thursday, May 6, 2010
  49. 49. Array.prototype.contains = function(element) { for (var i = 0; i < this.length; i++) { if (this[i] == element) return true; } return false; } [1, 2, 3].contains(); Thursday, May 6, 2010
  50. 50. Function.prototype.method = function(name, func) { this.prototype[name] = func; return this; } Thursday, May 6, 2010
  51. 51. String.method(‘trim’, function() { return this.replace(/^s+|s+$/g, ‘’); } “ tapir “.trim(); // “tapir” Thursday, May 6, 2010
  52. 52. Scope The function is the scope of the variables Thursday, May 6, 2010
  53. 53. Invocation Forms • Function form • sleep(10) • Method form • kjell.sleep(10) • kjell[“sleep”](10) • Constructor form • new sleep(10) • Apply form • sleep.apply(rudolph, 10) Thursday, May 6, 2010
  54. 54. this Invocation this this is an extra Form parameter that the global function object depends on the calling form method kjell constructor a new object apply rudolph Thursday, May 6, 2010
  55. 55. arguments • A special array like, DYNAMIC, parameter • All the arguments of the invocation Thursday, May 6, 2010
  56. 56. function sum() { var i, n = arguments.length, total = 0; for (i = 0; i < n; i += 1) { total += arguments[i]; } return total; } sum(1, 2, 3, 4); Thursday, May 6, 2010
  57. 57. Dynamic Compilation • eval • Evaluates a string and returns the result. • new Function(parameterArray, codeString) • Creates and returns a function. • var add=new Function("a", "b", "return a+b;"); Thursday, May 6, 2010
  58. 58. Global Variables Thursday, May 6, 2010
  59. 59. The global Object • Container for all variables • On browsers window == global • Any var not declared is global • Global variables are BAD Thursday, May 6, 2010
  60. 60. Good Practices Thursday, May 6, 2010
  61. 61. Cascade setFirst: function(name) { this.first = name; return this; } person .setFirst(“Anders”) .setLast(“Janmyr”) .setAge(40); Thursday, May 6, 2010
  62. 62. Modules var MyNamespace = {}; var MyNS = MyNS || {}; Thursday, May 6, 2010
  63. 63. Encapsulation var Esperanto = Esperanto || {}; Esperanto.Lab = function() { var privVar = "example"; function privFunc() { return privVar; } return { example: function() { return privFunc(); } } }() Thursday, May 6, 2010
  64. 64. Local Functions costData: function(current) { var data = {}; function addEntry(name, cost) { data[name + "PerHour"] = model.withTwoDec(cost/hours); data[name] = model.noDecimalsWithSeparator(cost); }; addEntry("interest", this.financialCost(current)), addEntry("depreciation", this.depreciationCost(current)), return data; }, Thursday, May 6, 2010
  65. 65. self = this attachFormListener: function(form, object) { var self = this; function populator(event) { self.populateFromForm(form, object); object.notify(); }; form.getElements().each(function(child) { child.observe('change', populator); }); }, Thursday, May 6, 2010
  66. 66. Mixins Object.mixin = function(destination, source) { for (property in source) destination[property] = source[property]; return destination; } Thursday, May 6, 2010
  67. 67. Aspects around: function(obj, fname, advice) { var oldFunc = obj[fname]; obj[fname] = function() { var args = [oldFunc, $A(arguments)].flatten(); return advice.apply(this, args); }; }, Thursday, May 6, 2010
  68. 68. Lab http://10.48.44.155/~andersjanmyr/ Thursday, May 6, 2010
  69. 69. Thank you! Anders Janmyr http://anders.janmyr.com anders.janmyr@jayway.com Thursday, May 6, 2010

×