SlideShare a Scribd company logo
1 of 85
Download to read offline
Javascript
                            the Programming Language of the Web
                                       Anders Janmyr
                                      http://anders.janmyr.com
                                     anders.janmyr@jayway.com




Tuesday, November 9, 2010
Ugly
     Javascript




Tuesday, November 9, 2010
Beautiful
        Javascript




Tuesday, November 9, 2010
Y-Combinator
                               Scheme (Lisp)
                            (define Y
                              (lambda (X)
                                ((lambda (procedure)
                                   (X (lambda (arg)
                                     ((procedure procedure)
                                     arg))))
                                 (lambda (procedure)
                                   (X (lambda (arg)
                                     ((procedure procedure)
                                     arg)))))))




Tuesday, November 9, 2010
Y-Combinator
                                  Javascript
                            function Y (X) {
                              return (function(procedure) {
                                return X(function(arg) {
                                  return procedure(procedure)(arg);
                                });
                              })(function(procedure) {
                                return X(function(arg) {
                                  return procedure(procedure)(arg);
                                });
                              });
                            }




Tuesday, November 9, 2010
Syntax

Tuesday, November 9, 2010
Values



Tuesday, November 9, 2010
Number

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

                   • NaN


Tuesday, November 9, 2010
Strings


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


Tuesday, November 9, 2010
Booleans

                   • true
                   • false
                   • Boolean()
                    • returns false for falsy values
                       • false, null, undefined, "", 0, NaN

Tuesday, November 9, 2010
null




Tuesday, November 9, 2010
Undefined

                   • Not even null
                   • Default value
                      • Parameters
                      • Arguments
                      • Non-existent members

Tuesday, November 9, 2010
Object


                   • Everything else
                   • Including functions


Tuesday, November 9, 2010
Statements



Tuesday, November 9, 2010
var

                   • Declares a variable
                   • If you forget, it will be defined globally!
                   • Scope of variable is the function


Tuesday, November 9, 2010
Conditionals
                   • If
                   • Switch - Case
               if (unit == 'Litre')
                  return value;
               else
                  return this.withTwoDecimals(value / 3.7854);




Tuesday, November 9, 2010
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]);
               }




Tuesday, November 9, 2010
Exceptions
               try {
                   setSelected(target);
                   f();
               } catch (err) {
                   console.log(err);
               }



               throw(anyObject)




Tuesday, November 9, 2010
Disruptive

                   • return [value]
                   • break [label]
                   • continue [label]
                   • throw object

Tuesday, November 9, 2010
Literals
                     number                         1.234
                     string            ‘anders’, “janmyr”
                     object                             {}
                     array                              []
                     function                 function() {}
                     regexp                    /^anders$/



Tuesday, November 9, 2010
typeof
                            type         typeof

                            object       'object'

                            function     'function'

                            array        'object'

                            number       'number'

                            string       'string'

                            boolean      'boolean'
                            null         'object'
                            undefined    'undefined'




Tuesday, November 9, 2010
Equality


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


Tuesday, November 9, 2010
Object




Tuesday, November 9, 2010
Object


                            Hashtable


Tuesday, November 9, 2010
Object


                            Dynamic


Tuesday, November 9, 2010
Object Literal


                            var empty_object = {};




Tuesday, November 9, 2010
var kjell = {
                                name: "Kjell",
                                "kind": "Malayan"
                            };




Tuesday, November 9, 2010
var kjell = {
                         name: "Kjell",
                         "kind": "Malayan"
                         address: {
                             country: "Denmark"
                         }
                     };


Tuesday, November 9, 2010
Retrieval
                  kjell.name    // “Kjell”
                  kjell["name"] // “Kjell”

                  // Denmark
                  kjell.address.country
                  kjell['address']["country"]



Tuesday, November 9, 2010
Retrieving non-existent
                       properties
                kjell.firstname // undefined
                kjell["NAME"]   // undefined
                kjell.home.country // Error




Tuesday, November 9, 2010
Setting non-existent
                                 properties
                       kjell.firstname = 'Sven';
                       kjell["NAME"] = 'SVEN';

                       kjell.firstname // 'Sven'




Tuesday, November 9, 2010
delete kjell.firstname

                     kjell.firstname // undefined




Tuesday, November 9, 2010
Prototypical




Tuesday, November 9, 2010
Prototypical Inheritance
                 using Object.create
                       var rudolph =
                           Object.create(kjell);

                       rudolph.name   // “Kjell”




Tuesday, November 9, 2010
Prototypical Inheritance
                                      name    Kjell
                                      kind   Malayan

                    id      a4r54ed
          prototype




Tuesday, November 9, 2010
rudolph.name = 'Rudolph';

                            rudolph.name // “Rudolph”
                            kjell.name   // “Kjell”

                            rudolph.kind // ‘Malayan’



Tuesday, November 9, 2010
rudolph.kind   // ‘Malayan’


                     kjell.kind = 'Baird';

                     rudolph.kind   // ‘Baird’




Tuesday, November 9, 2010
delete rudolph.name

                            rudolph.name // ‘Kjell’




Tuesday, November 9, 2010
Prototypical Inheritance
                              new Constructor();


                            Returns a new object with a link to
                                  Constructor.prototype




Tuesday, November 9, 2010
Prototypical Inheritance
              Object.create = function(o) {
                  function F() {}
                  F.prototype = o;
                  return new F();
              }




Tuesday, November 9, 2010
Prototypical Inheritance
                                      name     kjell
                                      kind   Malayan...

              id            a4r54ed
            name            rudolph
          prototype




Tuesday, November 9, 2010
Array




Tuesday, November 9, 2010
Arrays

                   • Array inherits from object
                   • Indexes are converted to strings
                   • Magic length property
                    • Always one larger than the highest int
                            property



Tuesday, November 9, 2010
Array Literals

                   • []
                   • names = [ ‘Rudolph’, ‘Kjell’, ‘Torsten’]
                   • typeof value == ‘object’
                    • value.constructor === Array

Tuesday, November 9, 2010
Array Methods
                   • concat
                   • join
                   • pop
                   • push
                   • slice
                   • sort
                   • splice
Tuesday, November 9, 2010
JSON
Tuesday, November 9, 2010
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"]
         }




Tuesday, November 9, 2010
Functions




Tuesday, November 9, 2010
Function


                             lambda
                            function() {};




Tuesday, November 9, 2010
Function

                            First class
                              object


Tuesday, November 9, 2010
Function Statement
                        function foo() {}

                        expands to

                        var foo = function foo() {};




Tuesday, November 9, 2010
Functions

                            Can be defined inside other functions!




Tuesday, November 9, 2010
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)
            };
        });
      }
    }


Tuesday, November 9, 2010
Methods

                        functions stored in objects




Tuesday, November 9, 2010
Built-in Prototypes
                   • Object.prototype
                   • Array.prototype
                   • Function.prototype
                   • Number.prototype
                   • String.prototype
                   • Boolean.prototype
Tuesday, November 9, 2010
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(3); // true




Tuesday, November 9, 2010
Function.prototype.method =
                       function(name, func) {
                         this.prototype[name] = func;
                         return this;
                     }




Tuesday, November 9, 2010
String.method(‘trim’, function() {
           return this.replace(/^s+|s+$/g, ‘’);
         }




          “ tapir “.trim(); // “tapir”




Tuesday, November 9, 2010
Scope

Tuesday, November 9, 2010
Scope

              The function is the scope of the
                         variables




Tuesday, November 9, 2010
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)
Tuesday, November 9, 2010
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




Tuesday, November 9, 2010
arguments

                   • A special array like, DYNAMIC, parameter

                   • All the arguments of the invocation


Tuesday, November 9, 2010
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);




Tuesday, November 9, 2010
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;");




Tuesday, November 9, 2010
Global
   Variables




Tuesday, November 9, 2010
The global Object

                   • Container for all variables
                   • On browsers window == global
                   • Any var not declared is global
                   • Global variables are BAD

Tuesday, November 9, 2010
Good
                            Practices




Tuesday, November 9, 2010
Modules

                            var MyNamespace = {};


                            var MyNS = MyNS || {};




Tuesday, November 9, 2010
Cascade
                        setFirst: function(name) {
                          this.first = name;
                          return this;
                        }


                    person
                     .setFirst(“Anders”)
                     .setLast(“Janmyr”)
                     .setAge(40);


Tuesday, November 9, 2010
Encapsulation
                            var Esperanto = Esperanto || {};

                            Esperanto.Lab = function() {
                                var privVar = "example";
                                function privFunc() {
                                    return privVar;
                                }

                                  return {
                                      example: function() {
                                           return privFunc();
                                      }
                                  }
                            }()




Tuesday, November 9, 2010
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;
                 },




Tuesday, November 9, 2010
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);
          });
      },




Tuesday, November 9, 2010
Mixins

               Object.mixin = function(destination, source) {
                  for (property in source)
                       destination[property] = source[property];
                  return destination;
               }




Tuesday, November 9, 2010
Enforcing New

                function User(first, last) {
                  if ( !(this instanceOf User))
                    return new User(first, last);

                       this.name = first + ‘ ‘ + last;
                }




Tuesday, November 9, 2010
Tools




Tuesday, November 9, 2010
Debuggers

                   • Firebug
                   • Apple Dev Tools
                   • Chrome Dev Tools
                   • Internet Explorer Developer Tools

Tuesday, November 9, 2010
CSS Tools

                   • http://codylindley.com/jqueryselectors/
                   • Selector Gadget
                   • Nokogiri
                            •   XML, HTML, SAX Parser




Tuesday, November 9, 2010
Minification

                   • JsMin
                            •   http://www.crockford.com/javascript/
                                jsmin.html

                   • YUI Compressor
                            •   http://developer.yahoo.com/yui/compressor/




Tuesday, November 9, 2010
Build Tools

                   • Rake
                   • SCons
                   • Ant
                   • Scripts

Tuesday, November 9, 2010
File Watchers
                   • xrefresh for Firefox and IE
                            •   http://xrefresh.binaryage.com/

                   • LiveReload for Safari and Chrome
                            •   http://github.com/mockko/livereload

                   • Watchr
                            •   gem install watchr


Tuesday, November 9, 2010
Localtunnel
                   • gem install localtunnel
                   • localtunnel -k my_public_ssh.key
                   • localtunnel 80
                            •   Port 80 is now publicly accessible from
                                http://8bv2.localtunnel.com ...

                            •

Tuesday, November 9, 2010
Tuesday, November 9, 2010
Lab


    http://10.48.44.155/~andersjanmyr/




Tuesday, November 9, 2010
Thank you!
                               Anders Janmyr
                              http://anders.janmyr.com
                             anders.janmyr@jayway.com




Tuesday, November 9, 2010

More Related Content

What's hot

Terence Barr - jdk7+8 - 24mai2011
Terence Barr - jdk7+8 - 24mai2011Terence Barr - jdk7+8 - 24mai2011
Terence Barr - jdk7+8 - 24mai2011Agora Group
 
Persistence And Documents
Persistence And DocumentsPersistence And Documents
Persistence And DocumentsSV.CO
 
CPython 3.2 SourceCodeReading
CPython 3.2 SourceCodeReadingCPython 3.2 SourceCodeReading
CPython 3.2 SourceCodeReadingShinya Kawanaka
 
Racing To Win: Using Race Conditions to Build Correct and Concurrent Software
Racing To Win: Using Race Conditions to Build Correct and Concurrent SoftwareRacing To Win: Using Race Conditions to Build Correct and Concurrent Software
Racing To Win: Using Race Conditions to Build Correct and Concurrent SoftwareFastly
 
Scala at HUJI PL Seminar 2008
Scala at HUJI PL Seminar 2008Scala at HUJI PL Seminar 2008
Scala at HUJI PL Seminar 2008Yardena Meymann
 
From Runnable and synchronized To atomically() and parallel()
From Runnable and synchronized To atomically() and parallel()From Runnable and synchronized To atomically() and parallel()
From Runnable and synchronized To atomically() and parallel()José Paumard
 
Javascript Basics - part 1
Javascript Basics - part 1Javascript Basics - part 1
Javascript Basics - part 1Kasia Drzyzga
 
Java/Scala Lab 2016. Григорий Кравцов: Реализация и тестирование DAO слоя с н...
Java/Scala Lab 2016. Григорий Кравцов: Реализация и тестирование DAO слоя с н...Java/Scala Lab 2016. Григорий Кравцов: Реализация и тестирование DAO слоя с н...
Java/Scala Lab 2016. Григорий Кравцов: Реализация и тестирование DAO слоя с н...GeeksLab Odessa
 
Turtle Graphics in Groovy
Turtle Graphics in GroovyTurtle Graphics in Groovy
Turtle Graphics in GroovyJim Driscoll
 
Few simple-type-tricks in scala
Few simple-type-tricks in scalaFew simple-type-tricks in scala
Few simple-type-tricks in scalaRuslan Shevchenko
 
みゆっき☆Think#7 「本気で学ぶJavascript」
みゆっき☆Think#7 「本気で学ぶJavascript」みゆっき☆Think#7 「本気で学ぶJavascript」
みゆっき☆Think#7 「本気で学ぶJavascript」techtalkdwango
 

What's hot (17)

05 subsetting
05 subsetting05 subsetting
05 subsetting
 
Terence Barr - jdk7+8 - 24mai2011
Terence Barr - jdk7+8 - 24mai2011Terence Barr - jdk7+8 - 24mai2011
Terence Barr - jdk7+8 - 24mai2011
 
Persistence And Documents
Persistence And DocumentsPersistence And Documents
Persistence And Documents
 
ECMA 入门
ECMA 入门ECMA 入门
ECMA 入门
 
CPython 3.2 SourceCodeReading
CPython 3.2 SourceCodeReadingCPython 3.2 SourceCodeReading
CPython 3.2 SourceCodeReading
 
Xtext Eclipse Con
Xtext Eclipse ConXtext Eclipse Con
Xtext Eclipse Con
 
All about scala
All about scalaAll about scala
All about scala
 
Scala jargon cheatsheet
Scala jargon cheatsheetScala jargon cheatsheet
Scala jargon cheatsheet
 
Racing To Win: Using Race Conditions to Build Correct and Concurrent Software
Racing To Win: Using Race Conditions to Build Correct and Concurrent SoftwareRacing To Win: Using Race Conditions to Build Correct and Concurrent Software
Racing To Win: Using Race Conditions to Build Correct and Concurrent Software
 
Scala at HUJI PL Seminar 2008
Scala at HUJI PL Seminar 2008Scala at HUJI PL Seminar 2008
Scala at HUJI PL Seminar 2008
 
From Runnable and synchronized To atomically() and parallel()
From Runnable and synchronized To atomically() and parallel()From Runnable and synchronized To atomically() and parallel()
From Runnable and synchronized To atomically() and parallel()
 
YUI Tidbits
YUI TidbitsYUI Tidbits
YUI Tidbits
 
Javascript Basics - part 1
Javascript Basics - part 1Javascript Basics - part 1
Javascript Basics - part 1
 
Java/Scala Lab 2016. Григорий Кравцов: Реализация и тестирование DAO слоя с н...
Java/Scala Lab 2016. Григорий Кравцов: Реализация и тестирование DAO слоя с н...Java/Scala Lab 2016. Григорий Кравцов: Реализация и тестирование DAO слоя с н...
Java/Scala Lab 2016. Григорий Кравцов: Реализация и тестирование DAO слоя с н...
 
Turtle Graphics in Groovy
Turtle Graphics in GroovyTurtle Graphics in Groovy
Turtle Graphics in Groovy
 
Few simple-type-tricks in scala
Few simple-type-tricks in scalaFew simple-type-tricks in scala
Few simple-type-tricks in scala
 
みゆっき☆Think#7 「本気で学ぶJavascript」
みゆっき☆Think#7 「本気で学ぶJavascript」みゆっき☆Think#7 「本気で学ぶJavascript」
みゆっき☆Think#7 「本気で学ぶJavascript」
 

Viewers also liked

Creative Direction
Creative DirectionCreative Direction
Creative Directionsara8487
 
Habits of a Responsible Programmer
Habits of a Responsible ProgrammerHabits of a Responsible Programmer
Habits of a Responsible Programmerandersjanmyr
 
Sara Allen Photography
Sara Allen PhotographySara Allen Photography
Sara Allen Photographysara8487
 
Global destruction (in 5 minutes)
Global destruction (in 5 minutes)Global destruction (in 5 minutes)
Global destruction (in 5 minutes)Reini Urban
 
Palma de mallorca
Palma de mallorcaPalma de mallorca
Palma de mallorcajose ruiz
 

Viewers also liked (8)

Rome
RomeRome
Rome
 
perlall
perlallperlall
perlall
 
Creative Direction
Creative DirectionCreative Direction
Creative Direction
 
Habits of a Responsible Programmer
Habits of a Responsible ProgrammerHabits of a Responsible Programmer
Habits of a Responsible Programmer
 
Sara Allen Photography
Sara Allen PhotographySara Allen Photography
Sara Allen Photography
 
Zebrafish day 2 part 1
Zebrafish day 2 part 1Zebrafish day 2 part 1
Zebrafish day 2 part 1
 
Global destruction (in 5 minutes)
Global destruction (in 5 minutes)Global destruction (in 5 minutes)
Global destruction (in 5 minutes)
 
Palma de mallorca
Palma de mallorcaPalma de mallorca
Palma de mallorca
 

Similar to Javascript the Language of the Web

Enterprise javascriptsession3
Enterprise javascriptsession3Enterprise javascriptsession3
Enterprise javascriptsession3Troy Miles
 
Parser combinators
Parser combinatorsParser combinators
Parser combinatorslifecoder
 
NoSQL: Death to Relational Databases(?)
NoSQL: Death to Relational Databases(?)NoSQL: Death to Relational Databases(?)
NoSQL: Death to Relational Databases(?)Ben Scofield
 
Paradigmas de programação funcional + objetos no liquidificador com scala
Paradigmas de programação funcional + objetos no liquidificador com scalaParadigmas de programação funcional + objetos no liquidificador com scala
Paradigmas de programação funcional + objetos no liquidificador com scalaBruno Oliveira
 
Beginners guide-concurrency
Beginners guide-concurrencyBeginners guide-concurrency
Beginners guide-concurrencyMichael Barker
 
De vuelta al pasado con SQL y stored procedures
De vuelta al pasado con SQL y stored proceduresDe vuelta al pasado con SQL y stored procedures
De vuelta al pasado con SQL y stored proceduresNorman Clarke
 
ぐだ生 Java入門第一回(equals hash code_tostring)
ぐだ生 Java入門第一回(equals hash code_tostring)ぐだ生 Java入門第一回(equals hash code_tostring)
ぐだ生 Java入門第一回(equals hash code_tostring)Makoto Yamazaki
 
Document relations
Document relationsDocument relations
Document relationsmartijnvg
 
Intro to pattern matching in scala
Intro to pattern matching in scalaIntro to pattern matching in scala
Intro to pattern matching in scalaJan Krag
 

Similar to Javascript the Language of the Web (20)

Enterprise javascriptsession3
Enterprise javascriptsession3Enterprise javascriptsession3
Enterprise javascriptsession3
 
Java scriptpatterns
Java scriptpatternsJava scriptpatterns
Java scriptpatterns
 
Java scriptpatterns
Java scriptpatternsJava scriptpatterns
Java scriptpatterns
 
Js in the open
Js in the openJs in the open
Js in the open
 
JavaScript 1.8.5: New Features Explored
JavaScript 1.8.5:  New Features ExploredJavaScript 1.8.5:  New Features Explored
JavaScript 1.8.5: New Features Explored
 
Obvious Secrets of JavaScript
Obvious Secrets of JavaScriptObvious Secrets of JavaScript
Obvious Secrets of JavaScript
 
Parser combinators
Parser combinatorsParser combinators
Parser combinators
 
Immutability
ImmutabilityImmutability
Immutability
 
Meet Couch DB
Meet Couch DBMeet Couch DB
Meet Couch DB
 
NoSQL: Death to Relational Databases(?)
NoSQL: Death to Relational Databases(?)NoSQL: Death to Relational Databases(?)
NoSQL: Death to Relational Databases(?)
 
Paradigmas de programação funcional + objetos no liquidificador com scala
Paradigmas de programação funcional + objetos no liquidificador com scalaParadigmas de programação funcional + objetos no liquidificador com scala
Paradigmas de programação funcional + objetos no liquidificador com scala
 
Scala 101-bcndevcon
Scala 101-bcndevconScala 101-bcndevcon
Scala 101-bcndevcon
 
Beginners guide-concurrency
Beginners guide-concurrencyBeginners guide-concurrency
Beginners guide-concurrency
 
De vuelta al pasado con SQL y stored procedures
De vuelta al pasado con SQL y stored proceduresDe vuelta al pasado con SQL y stored procedures
De vuelta al pasado con SQL y stored procedures
 
Json the-x-in-ajax1588
Json the-x-in-ajax1588Json the-x-in-ajax1588
Json the-x-in-ajax1588
 
ぐだ生 Java入門第一回(equals hash code_tostring)
ぐだ生 Java入門第一回(equals hash code_tostring)ぐだ生 Java入門第一回(equals hash code_tostring)
ぐだ生 Java入門第一回(equals hash code_tostring)
 
Document relations
Document relationsDocument relations
Document relations
 
Intro to pattern matching in scala
Intro to pattern matching in scalaIntro to pattern matching in scala
Intro to pattern matching in scala
 
Ruby struct
Ruby structRuby struct
Ruby struct
 
Intermediate JavaScript
Intermediate JavaScriptIntermediate JavaScript
Intermediate JavaScript
 

Recently uploaded

How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 

Recently uploaded (20)

How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 

Javascript the Language of the Web

  • 1. Javascript the Programming Language of the Web Anders Janmyr http://anders.janmyr.com anders.janmyr@jayway.com Tuesday, November 9, 2010
  • 2. Ugly Javascript Tuesday, November 9, 2010
  • 3. Beautiful Javascript Tuesday, November 9, 2010
  • 4. Y-Combinator Scheme (Lisp) (define Y (lambda (X) ((lambda (procedure) (X (lambda (arg) ((procedure procedure) arg)))) (lambda (procedure) (X (lambda (arg) ((procedure procedure) arg))))))) Tuesday, November 9, 2010
  • 5. Y-Combinator Javascript function Y (X) { return (function(procedure) { return X(function(arg) { return procedure(procedure)(arg); }); })(function(procedure) { return X(function(arg) { return procedure(procedure)(arg); }); }); } Tuesday, November 9, 2010
  • 8. Number • 64-bit floating point Double • 0.1 + 0.2 = 0.30000000000000004 • NaN Tuesday, November 9, 2010
  • 9. Strings • Immutable • ‘a string’ == “a string” Tuesday, November 9, 2010
  • 10. Booleans • true • false • Boolean() • returns false for falsy values • false, null, undefined, "", 0, NaN Tuesday, November 9, 2010
  • 12. Undefined • Not even null • Default value • Parameters • Arguments • Non-existent members Tuesday, November 9, 2010
  • 13. Object • Everything else • Including functions Tuesday, November 9, 2010
  • 15. var • Declares a variable • If you forget, it will be defined globally! • Scope of variable is the function Tuesday, November 9, 2010
  • 16. Conditionals • If • Switch - Case if (unit == 'Litre') return value; else return this.withTwoDecimals(value / 3.7854); Tuesday, November 9, 2010
  • 17. 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]); } Tuesday, November 9, 2010
  • 18. Exceptions try { setSelected(target); f(); } catch (err) { console.log(err); } throw(anyObject) Tuesday, November 9, 2010
  • 19. Disruptive • return [value] • break [label] • continue [label] • throw object Tuesday, November 9, 2010
  • 20. Literals number 1.234 string ‘anders’, “janmyr” object {} array [] function function() {} regexp /^anders$/ Tuesday, November 9, 2010
  • 21. typeof type typeof object 'object' function 'function' array 'object' number 'number' string 'string' boolean 'boolean' null 'object' undefined 'undefined' Tuesday, November 9, 2010
  • 22. Equality • 5 == “5” // true • 5 === “5” // false Tuesday, November 9, 2010
  • 24. Object Hashtable Tuesday, November 9, 2010
  • 25. Object Dynamic Tuesday, November 9, 2010
  • 26. Object Literal var empty_object = {}; Tuesday, November 9, 2010
  • 27. var kjell = { name: "Kjell", "kind": "Malayan" }; Tuesday, November 9, 2010
  • 28. var kjell = { name: "Kjell", "kind": "Malayan" address: { country: "Denmark" } }; Tuesday, November 9, 2010
  • 29. Retrieval kjell.name // “Kjell” kjell["name"] // “Kjell” // Denmark kjell.address.country kjell['address']["country"] Tuesday, November 9, 2010
  • 30. Retrieving non-existent properties kjell.firstname // undefined kjell["NAME"] // undefined kjell.home.country // Error Tuesday, November 9, 2010
  • 31. Setting non-existent properties kjell.firstname = 'Sven'; kjell["NAME"] = 'SVEN'; kjell.firstname // 'Sven' Tuesday, November 9, 2010
  • 32. delete kjell.firstname kjell.firstname // undefined Tuesday, November 9, 2010
  • 34. Prototypical Inheritance using Object.create var rudolph = Object.create(kjell); rudolph.name // “Kjell” Tuesday, November 9, 2010
  • 35. Prototypical Inheritance name Kjell kind Malayan id a4r54ed prototype Tuesday, November 9, 2010
  • 36. rudolph.name = 'Rudolph'; rudolph.name // “Rudolph” kjell.name // “Kjell” rudolph.kind // ‘Malayan’ Tuesday, November 9, 2010
  • 37. rudolph.kind // ‘Malayan’ kjell.kind = 'Baird'; rudolph.kind // ‘Baird’ Tuesday, November 9, 2010
  • 38. delete rudolph.name rudolph.name // ‘Kjell’ Tuesday, November 9, 2010
  • 39. Prototypical Inheritance new Constructor(); Returns a new object with a link to Constructor.prototype Tuesday, November 9, 2010
  • 40. Prototypical Inheritance Object.create = function(o) { function F() {} F.prototype = o; return new F(); } Tuesday, November 9, 2010
  • 41. Prototypical Inheritance name kjell kind Malayan... id a4r54ed name rudolph prototype Tuesday, November 9, 2010
  • 43. Arrays • Array inherits from object • Indexes are converted to strings • Magic length property • Always one larger than the highest int property Tuesday, November 9, 2010
  • 44. Array Literals • [] • names = [ ‘Rudolph’, ‘Kjell’, ‘Torsten’] • typeof value == ‘object’ • value.constructor === Array Tuesday, November 9, 2010
  • 45. Array Methods • concat • join • pop • push • slice • sort • splice Tuesday, November 9, 2010
  • 47. 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"] } Tuesday, November 9, 2010
  • 49. Function lambda function() {}; Tuesday, November 9, 2010
  • 50. Function First class object Tuesday, November 9, 2010
  • 51. Function Statement function foo() {} expands to var foo = function foo() {}; Tuesday, November 9, 2010
  • 52. Functions Can be defined inside other functions! Tuesday, November 9, 2010
  • 53. 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) }; }); } } Tuesday, November 9, 2010
  • 54. Methods functions stored in objects Tuesday, November 9, 2010
  • 55. Built-in Prototypes • Object.prototype • Array.prototype • Function.prototype • Number.prototype • String.prototype • Boolean.prototype Tuesday, November 9, 2010
  • 56. 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(3); // true Tuesday, November 9, 2010
  • 57. Function.prototype.method = function(name, func) { this.prototype[name] = func; return this; } Tuesday, November 9, 2010
  • 58. String.method(‘trim’, function() { return this.replace(/^s+|s+$/g, ‘’); } “ tapir “.trim(); // “tapir” Tuesday, November 9, 2010
  • 60. Scope The function is the scope of the variables Tuesday, November 9, 2010
  • 61. 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) Tuesday, November 9, 2010
  • 62. 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 Tuesday, November 9, 2010
  • 63. arguments • A special array like, DYNAMIC, parameter • All the arguments of the invocation Tuesday, November 9, 2010
  • 64. 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); Tuesday, November 9, 2010
  • 65. 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;"); Tuesday, November 9, 2010
  • 66. Global Variables Tuesday, November 9, 2010
  • 67. The global Object • Container for all variables • On browsers window == global • Any var not declared is global • Global variables are BAD Tuesday, November 9, 2010
  • 68. Good Practices Tuesday, November 9, 2010
  • 69. Modules var MyNamespace = {}; var MyNS = MyNS || {}; Tuesday, November 9, 2010
  • 70. Cascade setFirst: function(name) { this.first = name; return this; } person .setFirst(“Anders”) .setLast(“Janmyr”) .setAge(40); Tuesday, November 9, 2010
  • 71. Encapsulation var Esperanto = Esperanto || {}; Esperanto.Lab = function() { var privVar = "example"; function privFunc() { return privVar; } return { example: function() { return privFunc(); } } }() Tuesday, November 9, 2010
  • 72. 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; }, Tuesday, November 9, 2010
  • 73. 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); }); }, Tuesday, November 9, 2010
  • 74. Mixins Object.mixin = function(destination, source) { for (property in source) destination[property] = source[property]; return destination; } Tuesday, November 9, 2010
  • 75. Enforcing New function User(first, last) { if ( !(this instanceOf User)) return new User(first, last); this.name = first + ‘ ‘ + last; } Tuesday, November 9, 2010
  • 77. Debuggers • Firebug • Apple Dev Tools • Chrome Dev Tools • Internet Explorer Developer Tools Tuesday, November 9, 2010
  • 78. CSS Tools • http://codylindley.com/jqueryselectors/ • Selector Gadget • Nokogiri • XML, HTML, SAX Parser Tuesday, November 9, 2010
  • 79. Minification • JsMin • http://www.crockford.com/javascript/ jsmin.html • YUI Compressor • http://developer.yahoo.com/yui/compressor/ Tuesday, November 9, 2010
  • 80. Build Tools • Rake • SCons • Ant • Scripts Tuesday, November 9, 2010
  • 81. File Watchers • xrefresh for Firefox and IE • http://xrefresh.binaryage.com/ • LiveReload for Safari and Chrome • http://github.com/mockko/livereload • Watchr • gem install watchr Tuesday, November 9, 2010
  • 82. Localtunnel • gem install localtunnel • localtunnel -k my_public_ssh.key • localtunnel 80 • Port 80 is now publicly accessible from http://8bv2.localtunnel.com ... • Tuesday, November 9, 2010
  • 84. Lab http://10.48.44.155/~andersjanmyr/ Tuesday, November 9, 2010
  • 85. Thank you! Anders Janmyr http://anders.janmyr.com anders.janmyr@jayway.com Tuesday, November 9, 2010