Your SlideShare is downloading. ×
0
JS - Basics                             part 1Thursday, June 9, 2011
JS - overview                    •    JavaScript =/= DOM        •   Prototypal inheritance                                ...
VariablesThursday, June 9, 2011
Globals & Locals                    • only function scope                    • no block scope (ok, this is not exactly    ...
Globals & Locals                var a = 5;                (function() {                    var a = 7;                })();...
Globals & Locals                var a = 5;                (function() {                    a = 7;                })();    ...
Globals & Locals                • watch out for loops                         for(var i = 0; i < 3; i++) {                ...
var & let                    •    let - variable with block scope                    • implemented in JS 1.7 (part of ECMA...
var & let                <script type="application/                javascript;version=1.7">                var a = 6;     ...
var & let                 <script type="application/                 javascript;version=1.7">                 var a = 6;  ...
module pattern                    • extremely useful in apps that have more                         than one JS file       ...
module pattern                (function(){                     // om nom nom, do stuff, nothing gets out of here          ...
module pattern                var MyApp = function() {                    var privateVariable;                         fun...
variable types                    •    undefined - variable that has no value assigned                    •    null - obje...
Dynamic Typing                •        Data types can change                               var foo = 42;                  ...
Falsy Values                •        undefined                •        null                •        false                • ...
Falsy Values                0 == ; 0 == false;  == false // true                0 == undefined; 0 == null // false        ...
Literals vs Built-in                              Objects                var a = 1;                typeof a; // "number"  ...
Literals vs Built-in                              Objects                var a = [];                typeof a; // "object" ...
Built-in Objects                    •    Object            •   RegExp                    •    Function          •   Error ...
OperatorsThursday, June 9, 2011
Operators || and &&                function a(b){       function a(b){                    return b || 7;       return b &&...
Operator !!                • makes a boolean out of anything:                         !!0    !!   !!null   !!undefined   !...
Operators ~~ and |                • get integer from any number (fastest way)                         ~~3.75              ...
== && ===                    • == checks only the value                    • === checks also the type                    •...
ObjectsThursday, June 9, 2011
Objects                    •    almost everything is an object:                         •   functions, arrays, object lite...
Objects                var a = { b : om }, a1 = {   b : om }                var c = a;                a === a1 // false   ...
Objects                var obj = {key1 : 5}                obj.key1 // 5                obj[key1]; // 5                var...
Objects - creating           var obj = {               key1 : ”value”,       var obj = {};               key2 : 7,        ...
Arrays                    •    Indexes are converted to strings and used as                         names for retrieving v...
Arrays - length                                  property                         var arr = [];                         ar...
Arrays - deleting                            elements                var arr = [1, 2, 3] // [1, 2, 3]                delet...
Arrays - iterating                    •    Use for or while loop                    •    ECMA5 has more methods for iterat...
Arrays - iterating                Array.prototype.myArrMethod = function() { return thisIsMyArrMethod }                var...
FunctionsThursday, June 9, 2011
Functions                    •    Functions are first class objects – can be passed,                         returned or st...
Functions - defining                         function foo() {}                • is equivalent of:                         v...
Functions - closures                Function keeps a reference to its private variables                even after it has r...
Function - closures                    • Allow to use private variables and methods                    • Can cause problem...
<p id="help">Helpful notes will appear here</p>                <p>E-mail: <input type="text" id="email" name="email"></p> ...
for (var i = 0; i < helpText.length; i++) {                    var item = helpText[i];                    var elem = docum...
Functions - arguments                    • special ‘array like’ object accessible inside                         every fun...
Functions - arguments                function joiner(separator) {                    // make real array from arguments    ...
Functions - length                •        fnName.length - number of parameters function                         expects  ...
Function - invocation                •        Function form                         functionObject(arguments)             ...
Functions - this                    •    this is an extra parameter. Its value depends on the                         call...
Function - invocation in                     function form                         functionObject(arguments)              ...
Example                function oohLaLa() {                    alert(this == window)                }                oohLa...
Function - method                                   form                         myObject.methodName(args)                ...
Example                var ooh = {                    laLa: function() {                        alert(this === ooh)       ...
Function - constructor                         new functionObject(args)                • When a function is called with th...
Example                var Ooh = function() {}                Ooh.prototype.laLa = function(obj) {                    aler...
Function apply/call                fnObject.apply(thisObj,[arg1, arg2])                fnObject.call(thisObj, arg1, arg2) ...
Function - bind                         fnObject.bind(thisObj, arg1, arg2)                • Available in ECMA5            ...
Example                function sum() {                    var sum = 0;                    for(var i = 0; i < arguments.le...
To be (hopefully)                           continued with                             event loop,                        ...
Upcoming SlideShare
Loading in...5
×

Javascript Basics - part 1

3,991

Published on

Presentation from tech meeting @applicake on 6.06.2011

0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
3,991
On Slideshare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
43
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Transcript of "Javascript Basics - part 1"

  1. 1. JS - Basics part 1Thursday, June 9, 2011
  2. 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 objectThursday, June 9, 2011
  3. 3. VariablesThursday, June 9, 2011
  4. 4. Globals & Locals • only function scope • no block scope (ok, this is not exactly true...) • never, ever without varThursday, June 9, 2011
  5. 5. Globals & Locals var a = 5; (function() { var a = 7; })(); console.log(a) // 5Thursday, June 9, 2011
  6. 6. Globals & Locals var a = 5; (function() { a = 7; })(); console.log(a) // 7Thursday, June 9, 2011
  7. 7. Globals & Locals • watch out for loops for(var i = 0; i < 3; i++) { // be sure youre not making i global! }Thursday, June 9, 2011
  8. 8. var & let • let - variable with block scope • implemented in JS 1.7 (part of ECMA6) • sweet but not yet thereThursday, June 9, 2011
  9. 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. 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. 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/j4vhTiThursday, June 9, 2011
  12. 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 // nomThursday, June 9, 2011
  13. 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. 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. 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. 16. Falsy Values • undefined • null • false • NaN, 0 (both are numbers) • "" (empty strings) !null; !undefined; !0; !; !false; !NaN // trueThursday, June 9, 2011
  17. 17. Falsy Values 0 == ; 0 == false; == false // true 0 == undefined; 0 == null // false undefined == null // true NaN == NaN // falseThursday, June 9, 2011
  18. 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 & booleansThursday, June 9, 2011
  19. 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 waysThursday, June 9, 2011
  20. 20. Built-in Objects • Object • RegExp • Function • Error • Array • ... • String • Boolean • DateThursday, June 9, 2011
  21. 21. OperatorsThursday, June 9, 2011
  22. 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); // 0Thursday, June 9, 2011
  23. 23. Operator !! • makes a boolean out of anything: !!0 !! !!null !!undefined !!NaN // false !!5 !!om nom nom // true !![] !!{} // true !!function(){} // trueThursday, June 9, 2011
  24. 24. Operators ~~ and | • get integer from any number (fastest way) ~~3.75 0 | 3.75 parseInt(3.75)Thursday, June 9, 2011
  25. 25. == && === • == checks only the value • === checks also the type • always use === [] == ![] // true [] === ![] // falseThursday, June 9, 2011
  26. 26. ObjectsThursday, June 9, 2011
  27. 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 otherThursday, June 9, 2011
  28. 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. 29. Objects var obj = {key1 : 5} obj.key1 // 5 obj[key1]; // 5 var a = key1; obj[a] // 5 obj.someKey // undefined obj.someKey.value // errorThursday, June 9, 2011
  30. 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. 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. 32. Arrays - length property var arr = []; arr[3] = 1; arr.length // 4 arr // [undefined, undefined, undefined, 1]Thursday, June 9, 2011
  33. 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. 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 methodThursday, June 9, 2011
  35. 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, 1000Thursday, June 9, 2011
  36. 36. FunctionsThursday, June 9, 2011
  37. 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. 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. 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,whiteThursday, June 9, 2011
  40. 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 memoryThursday, June 9, 2011
  41. 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. 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. 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 sortThursday, June 9, 2011
  44. 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:3Thursday, June 9, 2011
  45. 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: 4Thursday, June 9, 2011
  46. 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. 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/jFFgUBThursday, June 9, 2011
  48. 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. 49. Example function oohLaLa() { alert(this == window) } oohLaLa(); // trueThursday, June 9, 2011
  50. 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 objectThursday, June 9, 2011
  51. 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. 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. 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); // trueThursday, June 9, 2011
  54. 54. Function apply/call fnObject.apply(thisObj,[arg1, arg2]) fnObject.call(thisObj, arg1, arg2) • this is set explicitelyThursday, June 9, 2011
  55. 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. 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 6Thursday, June 9, 2011
  57. 57. To be (hopefully) continued with event loop, inheritance & other JS sweetnessThursday, June 9, 2011
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×