SlideShare ist ein Scribd-Unternehmen logo
1 von 57
Downloaden Sie, um offline zu lesen
JS - Basics
                             part 1




Thursday, June 9, 2011
JS - overview
                    •    JavaScript =/= DOM        •   Prototypal inheritance
                                                       (objects not classes)
                    •    Dynamic language
                                                   •   Closures (lambda)
                    •    Loosely & dynamically
                         typed                     •   Event loop

                    •    Functional language       •   ECMA5

                    •    Almost everything is an   •   SSJS
                         object




Thursday, June 9, 2011
Variables



Thursday, June 9, 2011
Globals & Locals

                    • only function scope
                    • no block scope (ok, this is not exactly
                         true...)
                    • never, ever without var


Thursday, June 9, 2011
Globals & Locals
                var a = 5;

                (function() {
                    var a = 7;
                })();

                console.log(a) // 5




Thursday, June 9, 2011
Globals & Locals
                var a = 5;

                (function() {
                    a = 7;
                })();

                console.log(a) // 7




Thursday, June 9, 2011
Globals & Locals

                • watch out for loops
                         for(var i = 0; i < 3; i++) {

                             // be sure you're not making i global!

                         }




Thursday, June 9, 2011
var & let

                    •    let - variable with block scope

                    • implemented in JS 1.7 (part of ECMA6)
                    • sweet but not yet there


Thursday, June 9, 2011
var & let
                <script type="application/
                javascript;version=1.7">

                var a = 6;
                if(true) {
                    var b = 7;
                }
                console.log(a); // 6
                console.log(b); // 7

                </script>



Thursday, June 9, 2011
var & let
                 <script type="application/
                 javascript;version=1.7">

                 var a = 6;
                 if(true) {
                     let b = 7;
                 }
                 console.log(a); // 6
                 console.log(b); // Error: b is not defined

                 </script>



Thursday, June 9, 2011
module pattern
                    • extremely useful in apps that have more
                         than one JS file
                    • easy way to encapsulate and limit the
                         amount of global variables
                    • use please :)
                    • JavaScript Module Pattern: In-Depth - by
                         Ben Cherry http://bit.ly/j4vhTi


Thursday, June 9, 2011
module pattern
                (function(){
                     // om nom nom, do stuff, nothing gets out of here
                })()



                var MyApp = function() {
                    // do stuff and return some object for future use
                    return {
                        om : 'nom'
                    }
                } ();

                MyApp.om // nom




Thursday, June 9, 2011
module pattern
                var MyApp = function() {
                    var privateVariable;

                         function privateFunction(someVar) {
                             // mess around with privateVariable and someVar
                         }

                         var thisWillBePublic = function(someVar) {
                             return privateFunction(someVar)
                         }

                    return {
                        myAppMethod: thisWillBePublic
                    }
                } ();

                MyApp.myAppMethod();
Thursday, June 9, 2011
variable types
                    •    undefined - variable that has no value assigned

                    •    null - object with no value

                    •    boolean - true or false

                    •    string - 'this' "and that"

                    •    number - double precision 64bit number & NaN

                    •    object - everything else (yes, arrays and
                         functions too)


Thursday, June 9, 2011
Dynamic Typing
                •        Data types can change
                               var foo = 42;
                               foo = "Blah";

                •        „+” can convert to number
                               +"42" // 42

                •        „+” can convert to string
                               33 + " oops" // "33 oops"
                               "37" - 7 // 30
                               "37" + 7 // "377"
                •        Don’t kill the compiler - avoid changing types!



Thursday, June 9, 2011
Falsy Values
                •        undefined
                •        null
                •        false
                •        NaN, 0 (both are numbers)
                •        "" '' (empty strings)


                !null; !undefined; !0; !''; !false; !NaN // true




Thursday, June 9, 2011
Falsy Values

                0 == ''; 0 == false; '' == false // true



                0 == undefined; 0 == null // false

                undefined == null // true

                NaN == NaN // false




Thursday, June 9, 2011
Literals vs Built-in
                              Objects
                var a = 1;
                typeof a; // "number"
                a instanceof Number; // false
                a instanceof Object; // false

                var b = new Number(1);
                typeof b; // "object"
                b instanceof Number; // true
                b instanceof Object; // true

                a == b // true
                a === b // false


                Same happens with strings & booleans

Thursday, June 9, 2011
Literals vs Built-in
                              Objects
                var a = [];
                typeof a; // "object"
                a instanceof Array; // true
                a instanceof Object; // true

                var b = new Array(1);
                typeof b; // "object"
                b instanceof Array; // true
                b instanceof Object // true

                a == b // false - comparing references, not values!
                a === b // false - same case



           With arrays, objects and functions it works both ways
Thursday, June 9, 2011
Built-in Objects
                    •    Object            •   RegExp

                    •    Function          •   Error

                    •    Array             •   ...

                    •    String

                    •    Boolean

                    •    Date




Thursday, June 9, 2011
Operators



Thursday, June 9, 2011
Operators || and &&
                function a(b){       function a(b){
                    return b || 7;       return b && 7;
                }                    }

                a(); // 7            a(); // undefined
                a(9); // 9           a(9); // 7
                a([]); // []         a([]); // 7
                a(0); // 7           a(0); // 0




Thursday, June 9, 2011
Operator !!
                • makes a boolean out of anything:
                         !!0    !!''   !!null   !!undefined   !!NaN // false



                         !!5    !!'om nom nom' // true

                         !![]    !!{} // true

                         !!function(){} // true




Thursday, June 9, 2011
Operators ~~ and |

                • get integer from any number (fastest way)
                         ~~3.75

                         0 | 3.75

                         parseInt(3.75)




Thursday, June 9, 2011
== && ===

                    • == checks only the value
                    • === checks also the type
                    • always use ===
                         [] == ![]    // true

                         [] === ![]   // false




Thursday, June 9, 2011
Objects



Thursday, June 9, 2011
Objects
                    •    almost everything is an object:
                         •   functions, arrays, object literals, constructor instances..
                         •   everything that is not a string, number, boolean
                             (literals!), null or undefined
                    •    objects are always passed by reference (no clone method)
                    •    comparing objects compares references (no equal
                         method)
                    •    objects are dynamic - can be modified after creating
                    •    they can inherit from each other



Thursday, June 9, 2011
Objects
                var a = { b : 'om' }, a1 = {   b : 'om' }
                var c = a;

                a === a1 // false
                c === a // true

                a.b // 'om'
                c.b // 'om'

                c.b = 'nom'
                a.b // 'nom'

                (function(obj) {
                    obj.d = 'ninja!'
                })(a)

                c.d // ninja!




Thursday, June 9, 2011
Objects

                var obj = {key1 : 5}

                obj.key1 // 5
                obj['key1']; // 5
                var a = 'key1';
                obj[a] // 5

                obj.someKey // undefined
                obj.someKey.value // error




Thursday, June 9, 2011
Objects - creating
           var obj = {
               key1 : ”value”,       var obj = {};
               key2 : 7,             obj.key1 = 'str';
               key3 : true,          obj.key2 = 7;
               key4 : {},            obj.key3 = {};
               key5 : [],            obj.key3.boo = function() {}
               key6: function(){},
               key7: myFun
           }
           function myFun() {}




Thursday, June 9, 2011
Arrays
                    •    Indexes are converted to strings and used as
                         names for retrieving values.
                    •    Very efficient for sparse arrays.
                    •    length is not actual size of array but highest
                         index + 1
                    •    typeof [] returns ”object”
                    •    Arrays can be augmented (as any other object)


Thursday, June 9, 2011
Arrays - length
                                  property

                         var arr = [];

                         arr[3] = 1;

                         arr.length // 4

                         arr // [undefined, undefined, undefined, 1]




Thursday, June 9, 2011
Arrays - deleting
                            elements

                var arr = [1, 2, 3] // [1, 2, 3]
                delete arr[1] // [1, undefined, 3]

                var arr = [1, 2, 3] // [1, 2, 3]
                arr.splice(1, 1) // [1, 3]




Thursday, June 9, 2011
Arrays - iterating
                    •    Use for or while loop

                    •    ECMA5 has more methods for iteration like
                         forEach

                    •    for...in is dangerous and (usually) ineffective as
                         it uses not only array elements but also object
                         properties

                    •    for..in can be effective in case of sparse arrays
                         but has to be used with hasOwnProperty method



Thursday, June 9, 2011
Arrays - iterating
                Array.prototype.myArrMethod = function() { return 'thisIsMyArrMethod' }
                var arr = [];
                arr[3] = 3;
                arr[1000] = 1000;

                for(var i = 0, len = arr.length; i < len; i++){
                    console.log(arr[i])
                }
                // 3 x undefined, 3, 996 x undefined, 1000

                for(var i in arr) {
                    console.log(arr[i])
                }
                // 3, 1000, function () { return 'thisIsMyArrMethod' }

                for(var i in arr) {
                    if(arr.hasOwnProperty(i)) {
                        console.log(arr[i])
                    }
                }
                // 3, 1000

Thursday, June 9, 2011
Functions



Thursday, June 9, 2011
Functions
                    •    Functions are first class objects – can be passed,
                         returned or stored

                    •    typeof function(){} returns ”function”

                    •    In JS function is what in other languages is called
                         lambda
                    •    Functions can be defined inside each other
                    •    Functions return undefined if not set differently
                         (unless new operator is used)


Thursday, June 9, 2011
Functions - defining
                         function foo() {}

                • is equivalent of:
                         var foo = function() {}

                • Functions can be defined and called right away:
                         var foo = function(){}()
                         (function(a){})(123)


Thursday, June 9, 2011
Functions - closures
                Function keeps a reference to its private variables
                even after it has returned
                function setPuppyBasket(initialPuppy) {
                    var basket = [initialPuppy]
                    return function(puppy) {
                        if(puppy) {
                            basket.push(puppy)
                        }
                        return basket.toString();
                    }
                }

                var puppyBasket = setPuppyBasket('black');
                puppyBasket(); // 'black'
                puppyBasket('white') // 'black,white'
                puppyBasket('white') // 'black,white,white'

Thursday, June 9, 2011
Function - closures

                    • Allow to use private variables and methods
                    • Can cause problems when not used with
                         caution
                    • Excessive use of closures can affect script
                         performance - all objects are kept in
                         memory



Thursday, June 9, 2011
<p id="help">Helpful notes will appear here</p>
                <p>E-mail: <input type="text" id="email" name="email"></p>
                <p>Name: <input type="text" id="name" name="name"></p>
                <p>Age: <input type="text" id="age" name="age"></p>

                function showHelp(help) {
                  document.getElementById('help').innerHTML = help;
                }

                function setupHelp() {
                  var helpText = [
                       {'id': 'email', 'help': 'Your e-mail address'},
                       {'id': 'name', 'help': 'Your full name'},
                       {'id': 'age', 'help': 'Your age (you must be over 16)'}
                    ];

                     for (var i = 0; i < helpText.length; i++) {
                       var item = helpText[i];
                       document.getElementById(item.id).onfocus = function() {
                         showHelp(item.help);
                       }
                     }
                }

Thursday, June 9, 2011
for (var i = 0; i < helpText.length; i++) {
                    var item = helpText[i];
                    var elem = document.getElementById(item.id);
                    elem.onfocus = function() {
                        showHelp(item.help);
                    }
                }




                for (var i = 0; i < helpText.length; i++) {
                    var item = helpText[i];
                    var elem = document.getElementById(item.id);
                    elem.onfocus = function(helpItem) {
                        return function() {
                            showHelp(helpItem);
                        }
                    }(item.help)
                  }
                }



Thursday, June 9, 2011
Functions - arguments

                    • special ‘array like’ object accessible inside
                         every function
                    • contains all arguments with which function
                         was invoked
                    • has length property but no other array
                         methods like splice or sort



Thursday, June 9, 2011
Functions - arguments
                function joiner(separator) {
                    // make real array from arguments
                    var args = [].splice.call(arguments, 1)

                         return args.join(separator)
                }

                function joiner(separator) {
                    var len = arguments.length;
                    var joined = '';
                    for(var i = 1; i < len; i++) {
                        joined += arguments[i]
                        if(arguments[i+1]) {
                            joined += separator;
                        }
                    }
                    return joined;
                }

                joiner(':', 1, 2, 3); // 1:2:3


Thursday, June 9, 2011
Functions - length
                •        fnName.length - number of parameters function
                         expects
                •        arguments.length - number of parameters
                         actually passed to the function
                         function joiner(separator) {

                             console.log('joiner.length: ' + joiner.length)

                             console.log('arguments.length: ' + arguments.length)

                         }

                         joiner(':', 1, 2, 3);

                         // joiner.length: 1

                         // arguments.length: 4

Thursday, June 9, 2011
Function - invocation
                •        Function form
                         functionObject(arguments)

                •        Method form
                         thisObject.methodName(arguments)
                         thisObject["methodName"](arguments)

                •        Constructor form
                         new functionObject(arguments)

                •        Apply/call form
                         functionObject.apply(thisObj,[arguments])



Thursday, June 9, 2011
Functions - this
                    •    this is an extra parameter. Its value depends on the
                         calling form.
                    •    It’s the context in which function is called
                    •    this gives methods access to their objects

                    •    this is bound at invocation time

                    •    Treat it like something that will be changing

                    •    More information on this and context
                         http://j.mp/jFFgUB


Thursday, June 9, 2011
Function - invocation in
                     function form
                         functionObject(arguments)



                •        When a function is called in the function form, this is set
                         to the global object (always!)
                •        Most common usage but not very useful one
                •        It makes it harder to write helper functions within a method
                         because the helper function does not get access to the outer
                         this.
                         var that = this;

Thursday, June 9, 2011
Example

                function oohLaLa() {
                    alert(this == window)
                }
                oohLaLa(); // true




Thursday, June 9, 2011
Function - method
                                   form
                         myObject.methodName(args)
                         myObject["methodName"](args)


                • When a function is called in the method form, this is
                         set to myObject - the object containing the function.
                • This allows methods to have a reference to the parent
                         object


Thursday, June 9, 2011
Example
                var ooh = {
                    laLa: function() {
                        alert(this === ooh)
                    }
                }
                ooh.laLa(); // true

                var domNode = document.getElementById('elem');
                domNode.onclick = ooh.laLa; // false - context is domNode!

                var domNode = document.getElementById('elem');
                domNode.onclick = function() {
                    ooh.laLa(); // true - context is ooh object
                }




Thursday, June 9, 2011
Function - constructor
                         new functionObject(args)


                • When a function is called with the         new
                         operator, a new object is created and
                         assigned to this.

                • If there is not an explicit return value, then
                         this will be returned.


Thursday, June 9, 2011
Example

                var Ooh = function() {}
                Ooh.prototype.laLa = function(obj) {
                    alert(this === obj)
                }

                var myOoh = new Ooh(); // myOoh is created,
                                       // set to this and returned
                myOoh.laLa(myOoh); // true




Thursday, June 9, 2011
Function apply/call

                fnObject.apply(thisObj,[arg1, arg2])

                fnObject.call(thisObj, arg1, arg2)



                •        this is set explicitely




Thursday, June 9, 2011
Function - bind
                         fnObject.bind(thisObj, arg1, arg2)



                • Available in ECMA5
                • Binding this object & presetting the
                         arguments

                • Calling bind returns new - curried -
Thursday, June 9, 2011
Example
                function sum() {
                    var sum = 0;
                    for(var i = 0; i < arguments.length; i++) {
                        sum += arguments[i]
                    }
                    return sum
                }

                var addToOne = sum.bind(null, 1);
                addToOne(2) // this === null, returns 3

                var addToThree = sum.bind(null, 1, 2);
                addToThree(3) // this === null, returns 6




Thursday, June 9, 2011
To be (hopefully)
                           continued with
                             event loop,
                             inheritance
                                  &
                         other JS sweetness
Thursday, June 9, 2011

Weitere ähnliche Inhalte

Was ist angesagt?

Object Oriented Programming in JavaScript
Object Oriented Programming in JavaScriptObject Oriented Programming in JavaScript
Object Oriented Programming in JavaScript
zand3rs
 
JavaSE - The road forward
JavaSE - The road forwardJavaSE - The road forward
JavaSE - The road forward
eug3n_cojocaru
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced Javascript
Adieu
 

Was ist angesagt? (20)

Understanding JavaScript
Understanding JavaScriptUnderstanding JavaScript
Understanding JavaScript
 
My Favourite 10 Things about Xcode/ObjectiveC
My Favourite 10 Things about Xcode/ObjectiveCMy Favourite 10 Things about Xcode/ObjectiveC
My Favourite 10 Things about Xcode/ObjectiveC
 
Object Oriented Programming in JavaScript
Object Oriented Programming in JavaScriptObject Oriented Programming in JavaScript
Object Oriented Programming in JavaScript
 
JavaScript Programming
JavaScript ProgrammingJavaScript Programming
JavaScript Programming
 
JavaScript Inheritance
JavaScript InheritanceJavaScript Inheritance
JavaScript Inheritance
 
Interesting Facts About Javascript
Interesting Facts About JavascriptInteresting Facts About Javascript
Interesting Facts About Javascript
 
Javascript Prototypal Inheritance - Big Picture
Javascript Prototypal Inheritance - Big PictureJavascript Prototypal Inheritance - Big Picture
Javascript Prototypal Inheritance - Big Picture
 
Javascript Objects Deep Dive
Javascript Objects Deep DiveJavascript Objects Deep Dive
Javascript Objects Deep Dive
 
Testable Javascript
Testable JavascriptTestable Javascript
Testable Javascript
 
Scala 101-bcndevcon
Scala 101-bcndevconScala 101-bcndevcon
Scala 101-bcndevcon
 
Basic Javascript
Basic JavascriptBasic Javascript
Basic Javascript
 
ClassJS
ClassJSClassJS
ClassJS
 
Javascript
JavascriptJavascript
Javascript
 
JavaSE - The road forward
JavaSE - The road forwardJavaSE - The road forward
JavaSE - The road forward
 
JavaScript - From Birth To Closure
JavaScript - From Birth To ClosureJavaScript - From Birth To Closure
JavaScript - From Birth To Closure
 
JavaSE 7
JavaSE 7JavaSE 7
JavaSE 7
 
Enterprise js pratices
Enterprise js praticesEnterprise js pratices
Enterprise js pratices
 
Awesomeness of JavaScript…almost
Awesomeness of JavaScript…almostAwesomeness of JavaScript…almost
Awesomeness of JavaScript…almost
 
A JavaScript Master Class - From the Wows to the WTFs
A JavaScript Master Class - From the Wows to the WTFsA JavaScript Master Class - From the Wows to the WTFs
A JavaScript Master Class - From the Wows to the WTFs
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced Javascript
 

Ähnlich wie Javascript Basics - part 1

Enterprise javascriptsession3
Enterprise javascriptsession3Enterprise javascriptsession3
Enterprise javascriptsession3
Troy Miles
 
Javascript, Do you speak it!
Javascript, Do you speak it!Javascript, Do you speak it!
Javascript, Do you speak it!
Victor Porof
 
international PHP2011_ilia alshanetsky_Hidden Features of PHP
international PHP2011_ilia alshanetsky_Hidden Features of PHPinternational PHP2011_ilia alshanetsky_Hidden Features of PHP
international PHP2011_ilia alshanetsky_Hidden Features of PHP
smueller_sandsmedia
 
2011 JavaOne Fun with EJB 3.1 and OpenEJB
2011 JavaOne Fun with EJB 3.1 and OpenEJB2011 JavaOne Fun with EJB 3.1 and OpenEJB
2011 JavaOne Fun with EJB 3.1 and OpenEJB
David Blevins
 
The Solar Framework for PHP
The Solar Framework for PHPThe Solar Framework for PHP
The Solar Framework for PHP
ConFoo
 
Java SE 7 - The Platform Evolves, Dalibor Topić (Oracle)
Java SE 7 - The Platform Evolves, Dalibor Topić (Oracle)Java SE 7 - The Platform Evolves, Dalibor Topić (Oracle)
Java SE 7 - The Platform Evolves, Dalibor Topić (Oracle)
OpenBlend society
 

Ähnlich wie Javascript Basics - part 1 (20)

Enterprise javascriptsession3
Enterprise javascriptsession3Enterprise javascriptsession3
Enterprise javascriptsession3
 
Three Languages in Thirty Minutes (or so)
Three Languages in Thirty Minutes (or so)Three Languages in Thirty Minutes (or so)
Three Languages in Thirty Minutes (or so)
 
Javascript - How to avoid the bad parts
Javascript - How to avoid the bad partsJavascript - How to avoid the bad parts
Javascript - How to avoid the bad parts
 
Developing Cocoa Applications with macRuby
Developing Cocoa Applications with macRubyDeveloping Cocoa Applications with macRuby
Developing Cocoa Applications with macRuby
 
잘 알려지지 않은 Php 코드 활용하기
잘 알려지지 않은 Php 코드 활용하기잘 알려지지 않은 Php 코드 활용하기
잘 알려지지 않은 Php 코드 활용하기
 
Three Languages in Thirty Minutes
Three Languages in Thirty MinutesThree Languages in Thirty Minutes
Three Languages in Thirty Minutes
 
Three languages in thirty minutes
Three languages in thirty minutesThree languages in thirty minutes
Three languages in thirty minutes
 
Javascript, Do you speak it!
Javascript, Do you speak it!Javascript, Do you speak it!
Javascript, Do you speak it!
 
JavaScripts internals #1
JavaScripts internals #1JavaScripts internals #1
JavaScripts internals #1
 
international PHP2011_ilia alshanetsky_Hidden Features of PHP
international PHP2011_ilia alshanetsky_Hidden Features of PHPinternational PHP2011_ilia alshanetsky_Hidden Features of PHP
international PHP2011_ilia alshanetsky_Hidden Features of PHP
 
2011 JavaOne Fun with EJB 3.1 and OpenEJB
2011 JavaOne Fun with EJB 3.1 and OpenEJB2011 JavaOne Fun with EJB 3.1 and OpenEJB
2011 JavaOne Fun with EJB 3.1 and OpenEJB
 
The Solar Framework for PHP
The Solar Framework for PHPThe Solar Framework for PHP
The Solar Framework for PHP
 
Java SE 7 - The Platform Evolves, Dalibor Topić (Oracle)
Java SE 7 - The Platform Evolves, Dalibor Topić (Oracle)Java SE 7 - The Platform Evolves, Dalibor Topić (Oracle)
Java SE 7 - The Platform Evolves, Dalibor Topić (Oracle)
 
Future-proofing Your JavaScript Apps (Compact edition)
Future-proofing Your JavaScript Apps (Compact edition)Future-proofing Your JavaScript Apps (Compact edition)
Future-proofing Your JavaScript Apps (Compact edition)
 
Introducing the Ceylon Project
Introducing the Ceylon ProjectIntroducing the Ceylon Project
Introducing the Ceylon Project
 
Introducing the Ceylon Project - Gavin King presentation at QCon Beijing 2011
Introducing the Ceylon Project - Gavin King presentation at QCon Beijing 2011Introducing the Ceylon Project - Gavin King presentation at QCon Beijing 2011
Introducing the Ceylon Project - Gavin King presentation at QCon Beijing 2011
 
Ruby Xml Mapping
Ruby Xml MappingRuby Xml Mapping
Ruby Xml Mapping
 
Sqlpo Presentation
Sqlpo PresentationSqlpo Presentation
Sqlpo Presentation
 
Splash
SplashSplash
Splash
 
JavaScript Primer
JavaScript PrimerJavaScript Primer
JavaScript Primer
 

Javascript Basics - part 1

  • 1. JS - Basics part 1 Thursday, June 9, 2011
  • 2. JS - overview • JavaScript =/= DOM • Prototypal inheritance (objects not classes) • Dynamic language • Closures (lambda) • Loosely & dynamically typed • Event loop • Functional language • ECMA5 • Almost everything is an • SSJS object Thursday, June 9, 2011
  • 4. Globals & Locals • only function scope • no block scope (ok, this is not exactly true...) • never, ever without var Thursday, June 9, 2011
  • 5. Globals & Locals var a = 5; (function() { var a = 7; })(); console.log(a) // 5 Thursday, June 9, 2011
  • 6. Globals & Locals var a = 5; (function() { a = 7; })(); console.log(a) // 7 Thursday, June 9, 2011
  • 7. Globals & Locals • watch out for loops for(var i = 0; i < 3; i++) { // be sure you're not making i global! } Thursday, June 9, 2011
  • 8. var & let • let - variable with block scope • implemented in JS 1.7 (part of ECMA6) • sweet but not yet there Thursday, June 9, 2011
  • 9. var & let <script type="application/ javascript;version=1.7"> var a = 6; if(true) { var b = 7; } console.log(a); // 6 console.log(b); // 7 </script> Thursday, June 9, 2011
  • 10. var & let <script type="application/ javascript;version=1.7"> var a = 6; if(true) { let b = 7; } console.log(a); // 6 console.log(b); // Error: b is not defined </script> Thursday, June 9, 2011
  • 11. module pattern • extremely useful in apps that have more than one JS file • easy way to encapsulate and limit the amount of global variables • use please :) • JavaScript Module Pattern: In-Depth - by Ben Cherry http://bit.ly/j4vhTi Thursday, June 9, 2011
  • 12. module pattern (function(){ // om nom nom, do stuff, nothing gets out of here })() var MyApp = function() { // do stuff and return some object for future use return { om : 'nom' } } (); MyApp.om // nom Thursday, June 9, 2011
  • 13. module pattern var MyApp = function() { var privateVariable; function privateFunction(someVar) { // mess around with privateVariable and someVar } var thisWillBePublic = function(someVar) { return privateFunction(someVar) } return { myAppMethod: thisWillBePublic } } (); MyApp.myAppMethod(); Thursday, June 9, 2011
  • 14. variable types • undefined - variable that has no value assigned • null - object with no value • boolean - true or false • string - 'this' "and that" • number - double precision 64bit number & NaN • object - everything else (yes, arrays and functions too) Thursday, June 9, 2011
  • 15. Dynamic Typing • Data types can change var foo = 42; foo = "Blah"; • „+” can convert to number +"42" // 42 • „+” can convert to string 33 + " oops" // "33 oops" "37" - 7 // 30 "37" + 7 // "377" • Don’t kill the compiler - avoid changing types! Thursday, June 9, 2011
  • 16. Falsy Values • undefined • null • false • NaN, 0 (both are numbers) • "" '' (empty strings) !null; !undefined; !0; !''; !false; !NaN // true Thursday, June 9, 2011
  • 17. Falsy Values 0 == ''; 0 == false; '' == false // true 0 == undefined; 0 == null // false undefined == null // true NaN == NaN // false Thursday, June 9, 2011
  • 18. Literals vs Built-in Objects var a = 1; typeof a; // "number" a instanceof Number; // false a instanceof Object; // false var b = new Number(1); typeof b; // "object" b instanceof Number; // true b instanceof Object; // true a == b // true a === b // false Same happens with strings & booleans Thursday, June 9, 2011
  • 19. Literals vs Built-in Objects var a = []; typeof a; // "object" a instanceof Array; // true a instanceof Object; // true var b = new Array(1); typeof b; // "object" b instanceof Array; // true b instanceof Object // true a == b // false - comparing references, not values! a === b // false - same case With arrays, objects and functions it works both ways Thursday, June 9, 2011
  • 20. Built-in Objects • Object • RegExp • Function • Error • Array • ... • String • Boolean • Date Thursday, June 9, 2011
  • 22. Operators || and && function a(b){ function a(b){ return b || 7; return b && 7; } } a(); // 7 a(); // undefined a(9); // 9 a(9); // 7 a([]); // [] a([]); // 7 a(0); // 7 a(0); // 0 Thursday, June 9, 2011
  • 23. Operator !! • makes a boolean out of anything: !!0 !!'' !!null !!undefined !!NaN // false !!5 !!'om nom nom' // true !![] !!{} // true !!function(){} // true Thursday, June 9, 2011
  • 24. Operators ~~ and | • get integer from any number (fastest way) ~~3.75 0 | 3.75 parseInt(3.75) Thursday, June 9, 2011
  • 25. == && === • == checks only the value • === checks also the type • always use === [] == ![] // true [] === ![] // false Thursday, June 9, 2011
  • 27. Objects • almost everything is an object: • functions, arrays, object literals, constructor instances.. • everything that is not a string, number, boolean (literals!), null or undefined • objects are always passed by reference (no clone method) • comparing objects compares references (no equal method) • objects are dynamic - can be modified after creating • they can inherit from each other Thursday, June 9, 2011
  • 28. Objects var a = { b : 'om' }, a1 = { b : 'om' } var c = a; a === a1 // false c === a // true a.b // 'om' c.b // 'om' c.b = 'nom' a.b // 'nom' (function(obj) { obj.d = 'ninja!' })(a) c.d // ninja! Thursday, June 9, 2011
  • 29. Objects var obj = {key1 : 5} obj.key1 // 5 obj['key1']; // 5 var a = 'key1'; obj[a] // 5 obj.someKey // undefined obj.someKey.value // error Thursday, June 9, 2011
  • 30. Objects - creating var obj = { key1 : ”value”, var obj = {}; key2 : 7, obj.key1 = 'str'; key3 : true, obj.key2 = 7; key4 : {}, obj.key3 = {}; key5 : [], obj.key3.boo = function() {} key6: function(){}, key7: myFun } function myFun() {} Thursday, June 9, 2011
  • 31. Arrays • Indexes are converted to strings and used as names for retrieving values. • Very efficient for sparse arrays. • length is not actual size of array but highest index + 1 • typeof [] returns ”object” • Arrays can be augmented (as any other object) Thursday, June 9, 2011
  • 32. Arrays - length property var arr = []; arr[3] = 1; arr.length // 4 arr // [undefined, undefined, undefined, 1] Thursday, June 9, 2011
  • 33. Arrays - deleting elements var arr = [1, 2, 3] // [1, 2, 3] delete arr[1] // [1, undefined, 3] var arr = [1, 2, 3] // [1, 2, 3] arr.splice(1, 1) // [1, 3] Thursday, June 9, 2011
  • 34. Arrays - iterating • Use for or while loop • ECMA5 has more methods for iteration like forEach • for...in is dangerous and (usually) ineffective as it uses not only array elements but also object properties • for..in can be effective in case of sparse arrays but has to be used with hasOwnProperty method Thursday, June 9, 2011
  • 35. Arrays - iterating Array.prototype.myArrMethod = function() { return 'thisIsMyArrMethod' } var arr = []; arr[3] = 3; arr[1000] = 1000; for(var i = 0, len = arr.length; i < len; i++){ console.log(arr[i]) } // 3 x undefined, 3, 996 x undefined, 1000 for(var i in arr) { console.log(arr[i]) } // 3, 1000, function () { return 'thisIsMyArrMethod' } for(var i in arr) { if(arr.hasOwnProperty(i)) { console.log(arr[i]) } } // 3, 1000 Thursday, June 9, 2011
  • 37. Functions • Functions are first class objects – can be passed, returned or stored • typeof function(){} returns ”function” • In JS function is what in other languages is called lambda • Functions can be defined inside each other • Functions return undefined if not set differently (unless new operator is used) Thursday, June 9, 2011
  • 38. Functions - defining function foo() {} • is equivalent of: var foo = function() {} • Functions can be defined and called right away: var foo = function(){}() (function(a){})(123) Thursday, June 9, 2011
  • 39. Functions - closures Function keeps a reference to its private variables even after it has returned function setPuppyBasket(initialPuppy) { var basket = [initialPuppy] return function(puppy) { if(puppy) { basket.push(puppy) } return basket.toString(); } } var puppyBasket = setPuppyBasket('black'); puppyBasket(); // 'black' puppyBasket('white') // 'black,white' puppyBasket('white') // 'black,white,white' Thursday, June 9, 2011
  • 40. Function - closures • Allow to use private variables and methods • Can cause problems when not used with caution • Excessive use of closures can affect script performance - all objects are kept in memory Thursday, June 9, 2011
  • 41. <p id="help">Helpful notes will appear here</p> <p>E-mail: <input type="text" id="email" name="email"></p> <p>Name: <input type="text" id="name" name="name"></p> <p>Age: <input type="text" id="age" name="age"></p> function showHelp(help) { document.getElementById('help').innerHTML = help; } function setupHelp() { var helpText = [ {'id': 'email', 'help': 'Your e-mail address'}, {'id': 'name', 'help': 'Your full name'}, {'id': 'age', 'help': 'Your age (you must be over 16)'} ]; for (var i = 0; i < helpText.length; i++) { var item = helpText[i]; document.getElementById(item.id).onfocus = function() { showHelp(item.help); } } } Thursday, June 9, 2011
  • 42. for (var i = 0; i < helpText.length; i++) { var item = helpText[i]; var elem = document.getElementById(item.id); elem.onfocus = function() { showHelp(item.help); } } for (var i = 0; i < helpText.length; i++) { var item = helpText[i]; var elem = document.getElementById(item.id); elem.onfocus = function(helpItem) { return function() { showHelp(helpItem); } }(item.help) } } Thursday, June 9, 2011
  • 43. Functions - arguments • special ‘array like’ object accessible inside every function • contains all arguments with which function was invoked • has length property but no other array methods like splice or sort Thursday, June 9, 2011
  • 44. Functions - arguments function joiner(separator) { // make real array from arguments var args = [].splice.call(arguments, 1) return args.join(separator) } function joiner(separator) { var len = arguments.length; var joined = ''; for(var i = 1; i < len; i++) { joined += arguments[i] if(arguments[i+1]) { joined += separator; } } return joined; } joiner(':', 1, 2, 3); // 1:2:3 Thursday, June 9, 2011
  • 45. Functions - length • fnName.length - number of parameters function expects • arguments.length - number of parameters actually passed to the function function joiner(separator) { console.log('joiner.length: ' + joiner.length) console.log('arguments.length: ' + arguments.length) } joiner(':', 1, 2, 3); // joiner.length: 1 // arguments.length: 4 Thursday, June 9, 2011
  • 46. Function - invocation • Function form functionObject(arguments) • Method form thisObject.methodName(arguments) thisObject["methodName"](arguments) • Constructor form new functionObject(arguments) • Apply/call form functionObject.apply(thisObj,[arguments]) Thursday, June 9, 2011
  • 47. Functions - this • this is an extra parameter. Its value depends on the calling form. • It’s the context in which function is called • this gives methods access to their objects • this is bound at invocation time • Treat it like something that will be changing • More information on this and context http://j.mp/jFFgUB Thursday, June 9, 2011
  • 48. Function - invocation in function form functionObject(arguments) • When a function is called in the function form, this is set to the global object (always!) • Most common usage but not very useful one • It makes it harder to write helper functions within a method because the helper function does not get access to the outer this. var that = this; Thursday, June 9, 2011
  • 49. Example function oohLaLa() { alert(this == window) } oohLaLa(); // true Thursday, June 9, 2011
  • 50. Function - method form myObject.methodName(args) myObject["methodName"](args) • When a function is called in the method form, this is set to myObject - the object containing the function. • This allows methods to have a reference to the parent object Thursday, June 9, 2011
  • 51. Example var ooh = { laLa: function() { alert(this === ooh) } } ooh.laLa(); // true var domNode = document.getElementById('elem'); domNode.onclick = ooh.laLa; // false - context is domNode! var domNode = document.getElementById('elem'); domNode.onclick = function() { ooh.laLa(); // true - context is ooh object } Thursday, June 9, 2011
  • 52. Function - constructor new functionObject(args) • When a function is called with the new operator, a new object is created and assigned to this. • If there is not an explicit return value, then this will be returned. Thursday, June 9, 2011
  • 53. Example var Ooh = function() {} Ooh.prototype.laLa = function(obj) { alert(this === obj) } var myOoh = new Ooh(); // myOoh is created, // set to this and returned myOoh.laLa(myOoh); // true Thursday, June 9, 2011
  • 54. Function apply/call fnObject.apply(thisObj,[arg1, arg2]) fnObject.call(thisObj, arg1, arg2) • this is set explicitely Thursday, June 9, 2011
  • 55. Function - bind fnObject.bind(thisObj, arg1, arg2) • Available in ECMA5 • Binding this object & presetting the arguments • Calling bind returns new - curried - Thursday, June 9, 2011
  • 56. Example function sum() { var sum = 0; for(var i = 0; i < arguments.length; i++) { sum += arguments[i] } return sum } var addToOne = sum.bind(null, 1); addToOne(2) // this === null, returns 3 var addToThree = sum.bind(null, 1, 2); addToThree(3) // this === null, returns 6 Thursday, June 9, 2011
  • 57. To be (hopefully) continued with event loop, inheritance & other JS sweetness Thursday, June 9, 2011