SlideShare ist ein Scribd-Unternehmen logo
1 von 66
Awesomeness of JavaScript…almost
Twitter: #quintons
Github id: quintons

‘The most misunderstood language has become the worlds most
popular programming language’
Douglas Crockford – JavaScript architect, yahoo


‘JavaScript like the browsers is starting to move again’
Alex Russell – Software engineer, Chrome team and (ECMA) TC39 representative
Agenda

•   In the beginning
•   Objects, Functions
•   Overview of Scope
•   Overview of JS primitives and properties
•   Gotchers!
•   Questions…?
Agenda…for later

•   Inheritance and the class’less language
    •   Prototypical (differential) inheritance
•   Best Practices
•   Modulising
•   Multithreading with Webworkers
•   Frameworks what they can offer
•   Pollyfills, and how to use them
•   Etc….
In the beginning…
…what about JavaScript?

•   Java
•   Self
•   Scheme
•   LiveScript
…what about JavaScript?

•   Java
•   Self
•   Scheme
•   LiveScript
•   JavaScript
…what about JavaScript?

•   Java
•   Self
•   Scheme
•   LiveScript
•   JavaScript
•   ECMAScript
Current implementations (2012)

•   Chrome/V8
•   Firefox/SpiderMonkey
•   IE10/Chakra
•   Safari/SquirrelFish (Webkit browsers)
•   Opera/Carakan
JS Engine Performance (2011) – running JSLint

                3



               2.5



                2
milliseconds




               1.5



                1



               0.5



                0
                     Chrome 10    Chrome 13     Firefox 4       IE9           IE10   Opera 11   Safari 5


                                                            Browsers
               Datasource: http://javascript.crockford.com/performance.html
JavaScript is everywhere…

•   Built into every PC
•   Building Mobile apps
    •   Titainum,
    •   PhoneGap,
    •   Sencha Touch,
    •   jQuery mobile etc…
•   Server side – Rhino, NodeJs, Apache Sling, etc…
•   Every Browser
Proliferation of JS frameworks…
Frameworks using MVC

•   Backbone.js        •   JavaScriptMVC
•   Spine.js           •   SproutCore
•   Choco.js           •   Cappuccino
•   Agility.js         •   Google Web Toolkit (GWT)
•   Jamal.js           •   Google Closure
•   PureMVC            •   Ember
•   TrimJunction       •   Etc…
Proliferation of JS frameworks…
DOM, AJAX, CSS and Utility Frameworks

•   Jquery            •   Spry (Adobe)
•   Qooxdoo           •   Midori
•   ActiveJS          •   MooTools
•   ExtJS             •   GWT (Java)
•   Knockout          •   YUI
•   Eyeballs          •   Prototype
•   Sammy             •   Etc…
…What about Code?….
Objects, Functions

•   Run to completion
    •   No multithreading (almost)
    •   No type testing
•   All objects are mutable
•   Classless language – differential inheritance.
•   functions and closures – data hiding/private state
Objects, Functions

•   Data hiding
    function count(){
       var counter = 0;
       var increment = function(){
         counter += 1;
       }
       return function(){
         increment() // increments counter
         console.log(counter);
      }
    }

    var inc = count();

    inc(); // returns 1
    inc(); // returns 2
Objects, Functions

•   Functions are first class
    •   Can be passed as an argument
    •   Can be returned from a function
    •   Can be assigned to a variable
    •   Can be stored in an object or array
•   arguments passed by value
•   Function objects inherit from ‘Function.prototype’
Objects, Functions

•   Function
    •   Method
    •   Class
    •   Constructor
    •   Module
    •   Object
Objects, Functions

•   Function
    •       Defined with the Function constructor
        var func = new Function("x", "y", "return x * y");

    •       A function declaration
        function func(x, y){
          return x * y;
        }

    •       A function expression
        var func = function(x, y){
          return x * y;
        }
Objects, Functions

•   Function - A function declaration can be called before its
    declaration.
    // will work
    foo();
    function func(){
       // code...
    }

    // won't work - hoisting!
    func();
    var func = function(){
       // code
    }
Objects, Functions

•   Function - A function declaration can be called before its
    declaration.
    // will work
    foo();
    function func(){
       // code...
    }

    // won't work - hoisting!
    func();
    var func = function(){
       // code
    }



                                         …Why?….
Objects, Functions

•   Function
    •          hoisting of variables.
        (function(){
           function func(){
             // code
           }
           func()
        })

        (function(){
           var func = undefined;
           func() // returns 'undefined'

             func = function(){
               // code
             }
        })
Objects, Functions

•   Example of a first class function
    function collection(func){
      var items = [];
      return function(){
        items[items.length] = func;
        return items;
      }
    }

    function item(name){
      return 'item name is ' + name;
    }

    var coll = collection(item('item 1'));
    var items = coll()

    console.log(items[0])
Objects, Functions

•   Functions – arguments object
    •        Not a true array
        var args = Array.prototype.slice.call(arguments);

    •        …for example
        (function(){
           var args = Array.prototype.slice.call(arguments);
           var arr = [1, 2, 3, 4, 5, 6];

          console.log(args.slice(2)); // returns [3, 4, 5, 6]
          console.log(arr.slice(2)); // again…returns [3, 4, 5, 6]

        }(1, 2, 3, 4, 5, 6))
Objects, Functions

•   Functions – arguments object
    •    arguments only available inside a function

    var addNumbers = function(){
      var val = 0;
      for(var i = 0; i < arguments.length; i++){
         val += arguments[i];
      }
      return val;
    }

    addNumbers(10, 10, 10) // 30

    •    If too few arguments are passed, the remaining will be
         undefined
Objects, Functions

•   Functions – arguments
    •   Little sugar – ES3/5 usage
    function newMethod(val){
      return 5 * val
    }

    •   ES6 (Harmony) proposal
    function newMethod(val = 10){
      return 5 * val;
    }
Objects, Functions

•   Everything's an object
    [] instanceof Object === true
    {} instanceof Object === true
    String instanceof Object === true
    (function(){}) instanceof Object === true

•   And objects act like maps
    var obj = {
      value: 'foo',
      num: 298,
      arr: []
    }

    obj.value === obj['value'] // true
Objects, Functions

•   Every property has a unique key string associated
    to that object.
    var val = Object['uniqueName']
    var val = Object.uniqueName

    Object['uniqueName'] = val;
    Object.uniqueName = val;

    delete Object['uniqueName'];
    delete Object.uniqueName;

•   Make an instance of an object use the ‘new’
    keyword
    var variable = new Constructor(arg1, arg2, …);
Objects, Functions

•   Constructor
     function Storage(){
       var data = [];
       this.getData = function(index){
         return data[index];
       }
       this.addData = function(obj){
         data[data.length] = obj;
       }
     }

     var cords = new Storage();
     cords.addData({x: 40, y: 10});

     console.log(cords.getData(0).x); // 40

     console.log(cords.constructor); // 'Storage()'
Operators

•   Arithmetic
    * - + / %

•   Comparison
    === !== < > <= >=

•   Logical
    && || !

•   Bitwise
    & | ^ >> >>> <<
Error Catching/Throwing

•   Throw Statement
    try{
      // code...
    }catch(e){
      switch (e.name){
         case 'Error':
           //code...
           break;
         default:
           throw e;
         }
      }
    }

    /* JavaScript implementation exception types */
    'Error', 'EvalError', 'RangeError', 'SyntaxError', 'TypeError',
    'URIError'
this
Closures/scope and this

•   I do ‘this’ and you do that…
    •   ‘this’ keyword refers to the owner of the object that is
        invoked
    •   ‘this’ allows a method to know what object it is
        concerned with
    •   Without ‘this’ prototypical inheritance would not be
        possible.
Closures/scope and this

•   I do ‘this’ and you do that…continued
    •   function declaration/expression – ‘this’ assigned to the
        global scope
    •   function as a method – ‘this’ assigned to the object
        containing the function
    •   Inner function - ‘this’ does not get access to the outer
        function’s ‘this’
Closures/scope and this

•   I do ‘this’ and you do that…continued
    function Counter(){
      var that = this;

        this.message = null;
        this.count = function(msec){
          setTimeout(function(){
             that.showMessage('hello')
          }, msec)
        }
        this.showMessage = function(msg){
          console.log(this.message);
        }
    }

    var obj = new Counter();
    obj.message = 'help!';
    obj.count(1000);
Closures/scope and this

•   I do ‘this’ and you do that…continued
    •   You can change the context of what the object ‘this’
        refers to.
         function Logged(){
           this.log = function(message){
             console.log(message)
           }
         }

         function Item(){
           Logged.call(this)
         }

         var newItem = new Item();
         newItem.log('Ow my god an Error!') // writes out .message
Closures/scope and this

•   Only function creates scope, no block scope {}
    /* no block level scope */
    var arr = [1];
    var x = 'something';
    for(var i = 0; i < arr.length; i++){
      var x = 'another thing';
    }
    console.log(x) // x === 'another thing'

    var arr = [1];
    var x = 'something';
    for(var i = 0; i < arr.length; i++){
      (function(){
         var x = 'another thing';
      })
    }
    console.log(x) // x === 'something'
Closures/scope and this

•   ES5 to the rescue!...
    var arr = [1];
    var x = 'something';
    for(var i = 0; i < arr.length; i++){
      let x = 'another thing';
    }

    console.log(x) // x === 'something'


    var arr = [1];
    var x = 'something';
    for(var i = 0; i < arr.length; i++){
      let (x = 20, y = 20){
         console.log(x + y); // === 40
      };
    }
    console.log(x) // x === 'something'
Primitives

•   Numbers
•   Boolean
•   String
•   Undefined
•   Null
Primitives

•   Numbers
    •   1 type, 64 bit floating point (aka ‘double’)
    •   Associative Law does not hold true – ‘when dealing
        only with addition or only with multiplication we get
        the same result regardless of the order in which we do
        the operations’

        a = 0.1; b = 0.2; c = 0.3;
        (a + b) + c === a + (b + c) = false;

        (a + b) + c = 0.6000000000000001;
        a + (b + c) = 0.6;
Primitives

•   Numbers (continued)
    •   Max number (253) 9007199254740992
    •   Methods
        •   toExplonential()
        •   toFixed()
        •   toLocalString()
        •   toPrecision()
        •   toString()
        •   valueOf()
Primitives

•   Numbers (…and more)
    •   All numbers inherit from Number.prototype
    •   Numbers first class objects
        •   A number can be stored in a variable
        •   A number can be passed as a parameter
        •   A number can be returned from a function
        •   A number can be stored in an object
Primitives

•   Math object
    •   abs()     •   floor()    •   sqrt()
    •   acos()    •   log()      •   tan()
    •   asin()    •   max()
    •   atan()    •   min()
    •   atab2()   •   pow()
    •   ceil()    •   random()
    •   cos()     •   round()
    •   exp()     •   sin()
Primitives

•   parseInt/parseFloat
    •       Converts values into a number
    •       Converting string to a number stops at first non-
            numerical character

        parseInt('485px') === 485
        parseInt('08') === 0

        /* to resolve use 'base 10' */
        parseInt('08', 10) === 8

        parseInt('ABC', 10) === NaN

    •       parseFloat() defaults to base 10
Primitives




               Boolean
             True or False
                1 or 0
Primitives

•   String
    •       A sequence of 0 or more 16bit Unicode characters
    •       Strings are immutable

        /* Does NOT work */
        var foo = 'red';
        foo[0] = 't';
        console.log(foo); // still returns 'red'

        /* Does work */
        var foo = 'red'
        var replaceAt = function(str, index, c){
          return str.substr(0, index) + c + str.substr(index+c.length);
        }
        var foo = replaceAt(foo, 0 't') // foo is now 'ted'
Primitives

•   String (…continued)
    •       String literals can use single or double quotes
    •       Multilines – evil!

        var str = "this is 
               a multiline 
               string!"

    •       Converting number to a string
        var str1 = num.toString();
        var str2 = new String(num);
Primitives

•   String (…and more)
    •   Convert string to a number

    var num1 = +str;
    var num2 = Number(str);

    •   String.length
        •    ‘length’ property is the number of 16bit characters
             in a string
        •    All extended (outside of UCS-2) characters are
             counted as length of 2
Primitives

•   String methods
    •   charAt()         •   slice()
    •   charCodeAt()     •   split()
    •   concat()         •   substr()
    •   indexOf()        •   substring()
    •   lastIndexOf()    •   toLocalLowerCase()
    •   localCompare()   •   toLocalUpperCase()
    •   match()          •   toLowerCase()
    •   replace()        •   toString()
    •   search()         •   toUpperCase()
Primitives

•   String methods (…continued)
    •   trim() ES5
    •   trimLeft() ES5
    •   trimRight() ES5
Primitives

•   String methods (…continued)
    •   trim() ES5
    •   trimLeft() ES5
    •   trimRight() ES5




…What about ES3?….
Primitives

•   String methods (…continued)
    •        trim() – what about ES3?

        var str = $.trim(' str '); // JQuery
        var str = dojo.trim(' str '); // Dojo

        if(!String.prototype.trim !== 'function'){
           String.prototype.trim = function(){
             return this.replace(/^s+|s+$/g, '');
           }
        }

        var str = ' str '.trim();
Special Type of Object

•   Array
    •   Array inherits from ‘Object’
    •   Length of an array auto incremented
    •   No type required for each value
    •   Array.length
        •   Always 1 larger than the highest index
        •   Looping use a for loop
        •   Do not use a for…in loop with Arrays
Special Type of Object

•   Array
    •   Array inherits from ‘object’
    •   Length of an array auto incremented
    •   No type required for each value
    •   Array.length
        •   Always 1 larger than the highest index
        •   Looping use a for loop
        •   Do not use a for…in loop with Arrays

                                          …Why?….
Special Type of Object

•   Array (…continued)
    •        For in loop…
             ‘Array’ inherits from ‘Object’

        var obj = ['val', 2]

        Object.prototype.people = {
          val: function(){}
        }

        for(key in obj){
          if(obj.hasOwnProperty(key)){
             console.log(obj[key]);
          }
        }
Special Type of Object

•   Array (…continued)
    •   Array literals
        •   An array literal uses []
        •   It can contain any number of values of any type

        foo[foo.length] = val; // assign value
        var val = foo[0]; // retriving a value


    •   Deleting elements
        •   Removes the element but leaves a hole
Special Type of Object

•   Array (…continued)
    •       Deleting elements….creates a hole

        var foo = [1, 2, 3, 4, 5]

        delete foo[2];
        // foo = [1, 2, undefined, 4, 5]

        var delIndexArray = foo.splice(2,1);
        // foo = [1, 2, 4, 5];
        // delIndexArray = [3]


    •       Arrays are not true arrays – inherits from ‘Object’

    var myArray = [];
    (typeof myArray === 'object') // true
Special Type of Object

•   Array (…continued)
    •   Are you an array?

    if(Array.isArray !== 'function'){
       Array.isArray = function(arr){
         return Object.prototype.toString.call(arr) === '[object
    Array]';
       }
    }

    var arr = [1, 2, 3, 4, 5, 6];
    console.log(Array.isArray(arr)); // returns true

    $.isArray(arr); // (jQuery) returns true
    dojo.isArray(arr); (dojo) // returns true
    $type(arr) // (Mootools) returns 'array'
Special Type of Object

•   Date
    •   …..too many methods to list! (48)
    •   Y2K compliant – was not initially
…Watch out!….Gotchers…
Watch out!

•   Accidental collision with keywords used as properties
    var word_count = [];

    /* accidental collision fails with word 'constructor' */
    function wordCount(word){
      if(word_count[word]){
         word_count[word] += 1;
      }else{
         word_count[word] = 1;
      }
    }

    function wordCount (word){
      if(typeof word_count[word] === 'number'){
         word_count[word] += 1;
      }else{
         word_count[word] = 1;
      }
    }
Watch out!

•   For…in
    •   functions that inherit from prototype are included in
        the for..in enumeration
•   NaN
    •   Special number – Not a Number
    •   NaN is evil

        NaN + 5 == NaN;

    •   Use isNaN() to test for NaN
Watch out!

•   NaN (…continued)
    •       NaN === NaN = false
    •       NaN !== NaN = true
•   Silent Errors – automatic semicolon insertion
        return // <- returns 'undefined'
        {
          var foo = 'hello'
        }

•   Switch statement, will fall through if no break statement is
    declared
Watch out!

•   Immediately invocable function expression

    function(){
       // code
    }(); // syntax error! can't be immediately invoked

    (function(){
      // code
    }());

•   Infinity/-Infinity
    •    1/0 === Infinity
    •    -1/0 === -Infinity
    •    Test for Infinity/-Infinity use isFinite()
Watch out!

•   Relying on type coercion is not a good idea.

    null == undefined // true
    false == undefined // false
    false == 'false' // false
    '' == '0'      // false
    0 == ''        // true
    0 == '0'        // true


•   Always use ‘===‘ not ‘==‘

    null === undefined // false
    false === undefined // false
    false === 'false' // false
    '' === '0'     // false
    0 === ''       // false
    0 === '0'       // false
Watch out!

•   Operators and Concatenation

    var val = "3" + 0; // '30'

    var val = 6 + 3 + "4" // '94'

    var val = 6 + 3 + parseInt("4") // 13
Until next time…
Twitter: #quintons
Github id: quintons

Weitere ähnliche Inhalte

Was ist angesagt?

JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
David Padbury
 
JavaScript for PHP developers
JavaScript for PHP developersJavaScript for PHP developers
JavaScript for PHP developers
Stoyan Stefanov
 

Was ist angesagt? (20)

Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
 
Object Oriented JavaScript
Object Oriented JavaScriptObject Oriented JavaScript
Object Oriented JavaScript
 
Advanced Object-Oriented JavaScript
Advanced Object-Oriented JavaScriptAdvanced Object-Oriented JavaScript
Advanced Object-Oriented JavaScript
 
From object oriented to functional domain modeling
From object oriented to functional domain modelingFrom object oriented to functional domain modeling
From object oriented to functional domain modeling
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 
JavaScript Patterns
JavaScript PatternsJavaScript Patterns
JavaScript Patterns
 
Oojs 1.1
Oojs 1.1Oojs 1.1
Oojs 1.1
 
JavaScript Design Patterns
JavaScript Design PatternsJavaScript Design Patterns
JavaScript Design Patterns
 
Swift, functional programming, and the future of Objective-C
Swift, functional programming, and the future of Objective-CSwift, functional programming, and the future of Objective-C
Swift, functional programming, and the future of Objective-C
 
Automatic Reference Counting @ Pragma Night
Automatic Reference Counting @ Pragma NightAutomatic Reference Counting @ Pragma Night
Automatic Reference Counting @ Pragma Night
 
Java script
Java scriptJava script
Java script
 
Objective-C for Java Developers
Objective-C for Java DevelopersObjective-C for Java Developers
Objective-C for Java Developers
 
Prototype
PrototypePrototype
Prototype
 
JavaScript for PHP developers
JavaScript for PHP developersJavaScript for PHP developers
JavaScript for PHP developers
 
Objective-C Crash Course for Web Developers
Objective-C Crash Course for Web DevelopersObjective-C Crash Course for Web Developers
Objective-C Crash Course for Web Developers
 
Advance JS and oop
Advance JS and oopAdvance JS and oop
Advance JS and oop
 
RubyistのためのObjective-C入門
RubyistのためのObjective-C入門RubyistのためのObjective-C入門
RubyistのためのObjective-C入門
 
Automatic Reference Counting
Automatic Reference CountingAutomatic Reference Counting
Automatic Reference Counting
 
JavaScript - From Birth To Closure
JavaScript - From Birth To ClosureJavaScript - From Birth To Closure
JavaScript - From Birth To Closure
 
Ajaxworld
AjaxworldAjaxworld
Ajaxworld
 

Andere mochten auch

Strategy
StrategyStrategy
Strategy
Monjurul Habib
 
Solid waste mangement
Solid waste mangementSolid waste mangement
Solid waste mangement
alanhk1
 
Pre trip task cip recycling
Pre trip task cip recyclingPre trip task cip recycling
Pre trip task cip recycling
mgtaiwanrocs2013
 
recycle and reuse
recycle and reuserecycle and reuse
recycle and reuse
meerpatel
 
Basic Garbage Collection Techniques
Basic  Garbage  Collection  TechniquesBasic  Garbage  Collection  Techniques
Basic Garbage Collection Techniques
An Khuong
 

Andere mochten auch (20)

Garbage collection and Re-use
Garbage collection and Re-useGarbage collection and Re-use
Garbage collection and Re-use
 
Where Does All the \"Stuff\" Go?
Where Does All the \"Stuff\" Go?Where Does All the \"Stuff\" Go?
Where Does All the \"Stuff\" Go?
 
VCCS | New Faculty Seminar | EdTech Tour | 2014
VCCS | New Faculty Seminar | EdTech Tour | 2014VCCS | New Faculty Seminar | EdTech Tour | 2014
VCCS | New Faculty Seminar | EdTech Tour | 2014
 
Strategy
StrategyStrategy
Strategy
 
Waste sorting and recycling
Waste sorting and recyclingWaste sorting and recycling
Waste sorting and recycling
 
presentation
presentationpresentation
presentation
 
Garbage sorting machine and furniture
Garbage sorting machine and furnitureGarbage sorting machine and furniture
Garbage sorting machine and furniture
 
Waste sorting
Waste sortingWaste sorting
Waste sorting
 
Garbage cleaning sorting sureshnavandar
Garbage cleaning sorting sureshnavandarGarbage cleaning sorting sureshnavandar
Garbage cleaning sorting sureshnavandar
 
Ncert-solutions-for-class6-science
Ncert-solutions-for-class6-scienceNcert-solutions-for-class6-science
Ncert-solutions-for-class6-science
 
Solid waste mangement
Solid waste mangementSolid waste mangement
Solid waste mangement
 
Wastes management problem
Wastes management problemWastes management problem
Wastes management problem
 
Pre trip task cip recycling
Pre trip task cip recyclingPre trip task cip recycling
Pre trip task cip recycling
 
Scaffolding the Research Process
Scaffolding the Research ProcessScaffolding the Research Process
Scaffolding the Research Process
 
recycle and reuse
recycle and reuserecycle and reuse
recycle and reuse
 
Research proposal of solid waste management
Research proposal of solid waste managementResearch proposal of solid waste management
Research proposal of solid waste management
 
Basic Garbage Collection Techniques
Basic  Garbage  Collection  TechniquesBasic  Garbage  Collection  Techniques
Basic Garbage Collection Techniques
 
solid waste management garbage recycling waste water treatment specialized wa...
solid waste management garbage recycling waste water treatment specialized wa...solid waste management garbage recycling waste water treatment specialized wa...
solid waste management garbage recycling waste water treatment specialized wa...
 
Recycling Energy & Resources from Waste
Recycling Energy & Resources from WasteRecycling Energy & Resources from Waste
Recycling Energy & Resources from Waste
 
SOLID WASTE MANAGEMENT_TUP-TAGUIG
SOLID WASTE MANAGEMENT_TUP-TAGUIGSOLID WASTE MANAGEMENT_TUP-TAGUIG
SOLID WASTE MANAGEMENT_TUP-TAGUIG
 

Ähnlich wie Awesomeness of JavaScript…almost

Front end fundamentals session 1: javascript core
Front end fundamentals session 1: javascript coreFront end fundamentals session 1: javascript core
Front end fundamentals session 1: javascript core
Web Zhao
 
第7回みゆっき☆Think 本気で学ぶ JavaScript
第7回みゆっき☆Think 本気で学ぶ JavaScript第7回みゆっき☆Think 本気で学ぶ JavaScript
第7回みゆっき☆Think 本気で学ぶ JavaScript
Takuya Fujimura
 

Ähnlich wie Awesomeness of JavaScript…almost (20)

Lecture 03 - JQuery.pdf
Lecture 03 - JQuery.pdfLecture 03 - JQuery.pdf
Lecture 03 - JQuery.pdf
 
Douglas Crockford: Serversideness
Douglas Crockford: ServersidenessDouglas Crockford: Serversideness
Douglas Crockford: Serversideness
 
JavaScript For CSharp Developer
JavaScript For CSharp DeveloperJavaScript For CSharp Developer
JavaScript For CSharp Developer
 
JavaScript for real men
JavaScript for real menJavaScript for real men
JavaScript for real men
 
JS Essence
JS EssenceJS Essence
JS Essence
 
oojs
oojsoojs
oojs
 
Front end fundamentals session 1: javascript core
Front end fundamentals session 1: javascript coreFront end fundamentals session 1: javascript core
Front end fundamentals session 1: javascript core
 
第7回みゆっき☆Think 本気で学ぶ JavaScript
第7回みゆっき☆Think 本気で学ぶ JavaScript第7回みゆっき☆Think 本気で学ぶ JavaScript
第7回みゆっき☆Think 本気で学ぶ JavaScript
 
Angular2 for Beginners
Angular2 for BeginnersAngular2 for Beginners
Angular2 for Beginners
 
Everything is Permitted: Extending Built-ins
Everything is Permitted: Extending Built-insEverything is Permitted: Extending Built-ins
Everything is Permitted: Extending Built-ins
 
"Javascript" por Tiago Rodrigues
"Javascript" por Tiago Rodrigues"Javascript" por Tiago Rodrigues
"Javascript" por Tiago Rodrigues
 
jQuery introduction
jQuery introductionjQuery introduction
jQuery introduction
 
React Development with the MERN Stack
React Development with the MERN StackReact Development with the MERN Stack
React Development with the MERN Stack
 
Week3
Week3Week3
Week3
 
Javascript Everywhere
Javascript EverywhereJavascript Everywhere
Javascript Everywhere
 
Programming in java basics
Programming in java  basicsProgramming in java  basics
Programming in java basics
 
JSLT: JSON querying and transformation
JSLT: JSON querying and transformationJSLT: JSON querying and transformation
JSLT: JSON querying and transformation
 
Art of Javascript
Art of JavascriptArt of Javascript
Art of Javascript
 
Java Tutorial
Java Tutorial Java Tutorial
Java Tutorial
 
Learn JavaScript by modeling Rubik Cube
Learn JavaScript by modeling Rubik CubeLearn JavaScript by modeling Rubik Cube
Learn JavaScript by modeling Rubik Cube
 

Kürzlich hochgeladen

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Kürzlich hochgeladen (20)

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 

Awesomeness of JavaScript…almost

  • 1. Awesomeness of JavaScript…almost Twitter: #quintons Github id: quintons ‘The most misunderstood language has become the worlds most popular programming language’ Douglas Crockford – JavaScript architect, yahoo ‘JavaScript like the browsers is starting to move again’ Alex Russell – Software engineer, Chrome team and (ECMA) TC39 representative
  • 2. Agenda • In the beginning • Objects, Functions • Overview of Scope • Overview of JS primitives and properties • Gotchers! • Questions…?
  • 3. Agenda…for later • Inheritance and the class’less language • Prototypical (differential) inheritance • Best Practices • Modulising • Multithreading with Webworkers • Frameworks what they can offer • Pollyfills, and how to use them • Etc….
  • 5. …what about JavaScript? • Java • Self • Scheme • LiveScript
  • 6. …what about JavaScript? • Java • Self • Scheme • LiveScript • JavaScript
  • 7. …what about JavaScript? • Java • Self • Scheme • LiveScript • JavaScript • ECMAScript
  • 8. Current implementations (2012) • Chrome/V8 • Firefox/SpiderMonkey • IE10/Chakra • Safari/SquirrelFish (Webkit browsers) • Opera/Carakan
  • 9. JS Engine Performance (2011) – running JSLint 3 2.5 2 milliseconds 1.5 1 0.5 0 Chrome 10 Chrome 13 Firefox 4 IE9 IE10 Opera 11 Safari 5 Browsers Datasource: http://javascript.crockford.com/performance.html
  • 10. JavaScript is everywhere… • Built into every PC • Building Mobile apps • Titainum, • PhoneGap, • Sencha Touch, • jQuery mobile etc… • Server side – Rhino, NodeJs, Apache Sling, etc… • Every Browser
  • 11. Proliferation of JS frameworks… Frameworks using MVC • Backbone.js • JavaScriptMVC • Spine.js • SproutCore • Choco.js • Cappuccino • Agility.js • Google Web Toolkit (GWT) • Jamal.js • Google Closure • PureMVC • Ember • TrimJunction • Etc…
  • 12. Proliferation of JS frameworks… DOM, AJAX, CSS and Utility Frameworks • Jquery • Spry (Adobe) • Qooxdoo • Midori • ActiveJS • MooTools • ExtJS • GWT (Java) • Knockout • YUI • Eyeballs • Prototype • Sammy • Etc…
  • 14. Objects, Functions • Run to completion • No multithreading (almost) • No type testing • All objects are mutable • Classless language – differential inheritance. • functions and closures – data hiding/private state
  • 15. Objects, Functions • Data hiding function count(){ var counter = 0; var increment = function(){ counter += 1; } return function(){ increment() // increments counter console.log(counter); } } var inc = count(); inc(); // returns 1 inc(); // returns 2
  • 16. Objects, Functions • Functions are first class • Can be passed as an argument • Can be returned from a function • Can be assigned to a variable • Can be stored in an object or array • arguments passed by value • Function objects inherit from ‘Function.prototype’
  • 17. Objects, Functions • Function • Method • Class • Constructor • Module • Object
  • 18. Objects, Functions • Function • Defined with the Function constructor var func = new Function("x", "y", "return x * y"); • A function declaration function func(x, y){ return x * y; } • A function expression var func = function(x, y){ return x * y; }
  • 19. Objects, Functions • Function - A function declaration can be called before its declaration. // will work foo(); function func(){ // code... } // won't work - hoisting! func(); var func = function(){ // code }
  • 20. Objects, Functions • Function - A function declaration can be called before its declaration. // will work foo(); function func(){ // code... } // won't work - hoisting! func(); var func = function(){ // code } …Why?….
  • 21. Objects, Functions • Function • hoisting of variables. (function(){ function func(){ // code } func() }) (function(){ var func = undefined; func() // returns 'undefined' func = function(){ // code } })
  • 22. Objects, Functions • Example of a first class function function collection(func){ var items = []; return function(){ items[items.length] = func; return items; } } function item(name){ return 'item name is ' + name; } var coll = collection(item('item 1')); var items = coll() console.log(items[0])
  • 23. Objects, Functions • Functions – arguments object • Not a true array var args = Array.prototype.slice.call(arguments); • …for example (function(){ var args = Array.prototype.slice.call(arguments); var arr = [1, 2, 3, 4, 5, 6]; console.log(args.slice(2)); // returns [3, 4, 5, 6] console.log(arr.slice(2)); // again…returns [3, 4, 5, 6] }(1, 2, 3, 4, 5, 6))
  • 24. Objects, Functions • Functions – arguments object • arguments only available inside a function var addNumbers = function(){ var val = 0; for(var i = 0; i < arguments.length; i++){ val += arguments[i]; } return val; } addNumbers(10, 10, 10) // 30 • If too few arguments are passed, the remaining will be undefined
  • 25. Objects, Functions • Functions – arguments • Little sugar – ES3/5 usage function newMethod(val){ return 5 * val } • ES6 (Harmony) proposal function newMethod(val = 10){ return 5 * val; }
  • 26. Objects, Functions • Everything's an object [] instanceof Object === true {} instanceof Object === true String instanceof Object === true (function(){}) instanceof Object === true • And objects act like maps var obj = { value: 'foo', num: 298, arr: [] } obj.value === obj['value'] // true
  • 27. Objects, Functions • Every property has a unique key string associated to that object. var val = Object['uniqueName'] var val = Object.uniqueName Object['uniqueName'] = val; Object.uniqueName = val; delete Object['uniqueName']; delete Object.uniqueName; • Make an instance of an object use the ‘new’ keyword var variable = new Constructor(arg1, arg2, …);
  • 28. Objects, Functions • Constructor function Storage(){ var data = []; this.getData = function(index){ return data[index]; } this.addData = function(obj){ data[data.length] = obj; } } var cords = new Storage(); cords.addData({x: 40, y: 10}); console.log(cords.getData(0).x); // 40 console.log(cords.constructor); // 'Storage()'
  • 29. Operators • Arithmetic * - + / % • Comparison === !== < > <= >= • Logical && || ! • Bitwise & | ^ >> >>> <<
  • 30. Error Catching/Throwing • Throw Statement try{ // code... }catch(e){ switch (e.name){ case 'Error': //code... break; default: throw e; } } } /* JavaScript implementation exception types */ 'Error', 'EvalError', 'RangeError', 'SyntaxError', 'TypeError', 'URIError'
  • 31. this
  • 32. Closures/scope and this • I do ‘this’ and you do that… • ‘this’ keyword refers to the owner of the object that is invoked • ‘this’ allows a method to know what object it is concerned with • Without ‘this’ prototypical inheritance would not be possible.
  • 33. Closures/scope and this • I do ‘this’ and you do that…continued • function declaration/expression – ‘this’ assigned to the global scope • function as a method – ‘this’ assigned to the object containing the function • Inner function - ‘this’ does not get access to the outer function’s ‘this’
  • 34. Closures/scope and this • I do ‘this’ and you do that…continued function Counter(){ var that = this; this.message = null; this.count = function(msec){ setTimeout(function(){ that.showMessage('hello') }, msec) } this.showMessage = function(msg){ console.log(this.message); } } var obj = new Counter(); obj.message = 'help!'; obj.count(1000);
  • 35. Closures/scope and this • I do ‘this’ and you do that…continued • You can change the context of what the object ‘this’ refers to. function Logged(){ this.log = function(message){ console.log(message) } } function Item(){ Logged.call(this) } var newItem = new Item(); newItem.log('Ow my god an Error!') // writes out .message
  • 36. Closures/scope and this • Only function creates scope, no block scope {} /* no block level scope */ var arr = [1]; var x = 'something'; for(var i = 0; i < arr.length; i++){ var x = 'another thing'; } console.log(x) // x === 'another thing' var arr = [1]; var x = 'something'; for(var i = 0; i < arr.length; i++){ (function(){ var x = 'another thing'; }) } console.log(x) // x === 'something'
  • 37. Closures/scope and this • ES5 to the rescue!... var arr = [1]; var x = 'something'; for(var i = 0; i < arr.length; i++){ let x = 'another thing'; } console.log(x) // x === 'something' var arr = [1]; var x = 'something'; for(var i = 0; i < arr.length; i++){ let (x = 20, y = 20){ console.log(x + y); // === 40 }; } console.log(x) // x === 'something'
  • 38. Primitives • Numbers • Boolean • String • Undefined • Null
  • 39. Primitives • Numbers • 1 type, 64 bit floating point (aka ‘double’) • Associative Law does not hold true – ‘when dealing only with addition or only with multiplication we get the same result regardless of the order in which we do the operations’ a = 0.1; b = 0.2; c = 0.3; (a + b) + c === a + (b + c) = false; (a + b) + c = 0.6000000000000001; a + (b + c) = 0.6;
  • 40. Primitives • Numbers (continued) • Max number (253) 9007199254740992 • Methods • toExplonential() • toFixed() • toLocalString() • toPrecision() • toString() • valueOf()
  • 41. Primitives • Numbers (…and more) • All numbers inherit from Number.prototype • Numbers first class objects • A number can be stored in a variable • A number can be passed as a parameter • A number can be returned from a function • A number can be stored in an object
  • 42. Primitives • Math object • abs() • floor() • sqrt() • acos() • log() • tan() • asin() • max() • atan() • min() • atab2() • pow() • ceil() • random() • cos() • round() • exp() • sin()
  • 43. Primitives • parseInt/parseFloat • Converts values into a number • Converting string to a number stops at first non- numerical character parseInt('485px') === 485 parseInt('08') === 0 /* to resolve use 'base 10' */ parseInt('08', 10) === 8 parseInt('ABC', 10) === NaN • parseFloat() defaults to base 10
  • 44. Primitives Boolean True or False 1 or 0
  • 45. Primitives • String • A sequence of 0 or more 16bit Unicode characters • Strings are immutable /* Does NOT work */ var foo = 'red'; foo[0] = 't'; console.log(foo); // still returns 'red' /* Does work */ var foo = 'red' var replaceAt = function(str, index, c){ return str.substr(0, index) + c + str.substr(index+c.length); } var foo = replaceAt(foo, 0 't') // foo is now 'ted'
  • 46. Primitives • String (…continued) • String literals can use single or double quotes • Multilines – evil! var str = "this is a multiline string!" • Converting number to a string var str1 = num.toString(); var str2 = new String(num);
  • 47. Primitives • String (…and more) • Convert string to a number var num1 = +str; var num2 = Number(str); • String.length • ‘length’ property is the number of 16bit characters in a string • All extended (outside of UCS-2) characters are counted as length of 2
  • 48. Primitives • String methods • charAt() • slice() • charCodeAt() • split() • concat() • substr() • indexOf() • substring() • lastIndexOf() • toLocalLowerCase() • localCompare() • toLocalUpperCase() • match() • toLowerCase() • replace() • toString() • search() • toUpperCase()
  • 49. Primitives • String methods (…continued) • trim() ES5 • trimLeft() ES5 • trimRight() ES5
  • 50. Primitives • String methods (…continued) • trim() ES5 • trimLeft() ES5 • trimRight() ES5 …What about ES3?….
  • 51. Primitives • String methods (…continued) • trim() – what about ES3? var str = $.trim(' str '); // JQuery var str = dojo.trim(' str '); // Dojo if(!String.prototype.trim !== 'function'){ String.prototype.trim = function(){ return this.replace(/^s+|s+$/g, ''); } } var str = ' str '.trim();
  • 52. Special Type of Object • Array • Array inherits from ‘Object’ • Length of an array auto incremented • No type required for each value • Array.length • Always 1 larger than the highest index • Looping use a for loop • Do not use a for…in loop with Arrays
  • 53. Special Type of Object • Array • Array inherits from ‘object’ • Length of an array auto incremented • No type required for each value • Array.length • Always 1 larger than the highest index • Looping use a for loop • Do not use a for…in loop with Arrays …Why?….
  • 54. Special Type of Object • Array (…continued) • For in loop… ‘Array’ inherits from ‘Object’ var obj = ['val', 2] Object.prototype.people = { val: function(){} } for(key in obj){ if(obj.hasOwnProperty(key)){ console.log(obj[key]); } }
  • 55. Special Type of Object • Array (…continued) • Array literals • An array literal uses [] • It can contain any number of values of any type foo[foo.length] = val; // assign value var val = foo[0]; // retriving a value • Deleting elements • Removes the element but leaves a hole
  • 56. Special Type of Object • Array (…continued) • Deleting elements….creates a hole var foo = [1, 2, 3, 4, 5] delete foo[2]; // foo = [1, 2, undefined, 4, 5] var delIndexArray = foo.splice(2,1); // foo = [1, 2, 4, 5]; // delIndexArray = [3] • Arrays are not true arrays – inherits from ‘Object’ var myArray = []; (typeof myArray === 'object') // true
  • 57. Special Type of Object • Array (…continued) • Are you an array? if(Array.isArray !== 'function'){ Array.isArray = function(arr){ return Object.prototype.toString.call(arr) === '[object Array]'; } } var arr = [1, 2, 3, 4, 5, 6]; console.log(Array.isArray(arr)); // returns true $.isArray(arr); // (jQuery) returns true dojo.isArray(arr); (dojo) // returns true $type(arr) // (Mootools) returns 'array'
  • 58. Special Type of Object • Date • …..too many methods to list! (48) • Y2K compliant – was not initially
  • 60. Watch out! • Accidental collision with keywords used as properties var word_count = []; /* accidental collision fails with word 'constructor' */ function wordCount(word){ if(word_count[word]){ word_count[word] += 1; }else{ word_count[word] = 1; } } function wordCount (word){ if(typeof word_count[word] === 'number'){ word_count[word] += 1; }else{ word_count[word] = 1; } }
  • 61. Watch out! • For…in • functions that inherit from prototype are included in the for..in enumeration • NaN • Special number – Not a Number • NaN is evil NaN + 5 == NaN; • Use isNaN() to test for NaN
  • 62. Watch out! • NaN (…continued) • NaN === NaN = false • NaN !== NaN = true • Silent Errors – automatic semicolon insertion return // <- returns 'undefined' { var foo = 'hello' } • Switch statement, will fall through if no break statement is declared
  • 63. Watch out! • Immediately invocable function expression function(){ // code }(); // syntax error! can't be immediately invoked (function(){ // code }()); • Infinity/-Infinity • 1/0 === Infinity • -1/0 === -Infinity • Test for Infinity/-Infinity use isFinite()
  • 64. Watch out! • Relying on type coercion is not a good idea. null == undefined // true false == undefined // false false == 'false' // false '' == '0' // false 0 == '' // true 0 == '0' // true • Always use ‘===‘ not ‘==‘ null === undefined // false false === undefined // false false === 'false' // false '' === '0' // false 0 === '' // false 0 === '0' // false
  • 65. Watch out! • Operators and Concatenation var val = "3" + 0; // '30' var val = 6 + 3 + "4" // '94' var val = 6 + 3 + parseInt("4") // 13
  • 66. Until next time… Twitter: #quintons Github id: quintons

Hinweis der Redaktion

  1. 1993 at National Center for Super Computing Applications – created mosaic (1st popular browser)1994 Jim clark (founder of Silicon Graphics) setup company Mosaic CorporationSued for name – changed to Netscape Corporation– created Netscape Navigator
  2. 1995 Netscape Hired Brendon Ike - (working at Silicon Graphics), Scripting language ‘Mocha’ (Scheme, Java, Self)Became LiveScript - Server/Client scriptingDecember 1995 licensing agreement with SunLiveScript -&gt; JavaScript
  3. Microsoft reversed engineered JavaScript – became JscriptNetscape went to W3C for standard (no show) Netscape Landed at European Computer Manufacturers Association (ECMA)Unfortunately -&gt; Microsoft on Committee (standards body)JavaScript – Registered Trade Mark.name came to be ECMAScript (ECMAScript 262)
  4. Wanted Standard name, name came to be ECMAScript (ECMAScript 262)1997 – ES11999 – ES34th Edition Abandoned2009 – ES52013 – ES6 (ES Harmony)
  5. Function –behavior containing data NOT data containing behaviour
  6. 255 arguments – max length.
  7. Maps – JSONArrays act like Maps
  8. Most important for ‘Prototypical Inheritance’The unfortunate name – hard to talk about
  9. - in a browser that is the Window object
  10. &gt; As said before “‘this’ keyword refers to the owner of the object that is invoked”
  11. George Boole - 1854 in his book ‘An investigation of the Laws of Thought’.
  12. UCS-2 internally, not quite UTF-16Any character coming under UCS-2, outside of UTF-16 maybe counted as length === 2
  13. New String() is GC’edString literals are NOT GC’ed
  14. If word is ‘Constructor’ fails – already contains word inherited from Object.ECMA Specification states ‘a browser maker can add new properties to any prototype’