Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Awesomeness of JavaScript…almost

1,406 views

Published on

an introduction to Javascript, its gotchas and construction.

Published in: Technology
  • Be the first to comment

  • Be the first to like this

Awesomeness of JavaScript…almost

  1. 1. Awesomeness of JavaScript…almostTwitter: #quintonsGithub id: quintons‘The most misunderstood language has become the worlds mostpopular 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. 2. Agenda• In the beginning• Objects, Functions• Overview of Scope• Overview of JS primitives and properties• Gotchers!• Questions…?
  3. 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….
  4. 4. In the beginning…
  5. 5. …what about JavaScript?• Java• Self• Scheme• LiveScript
  6. 6. …what about JavaScript?• Java• Self• Scheme• LiveScript• JavaScript
  7. 7. …what about JavaScript?• Java• Self• Scheme• LiveScript• JavaScript• ECMAScript
  8. 8. Current implementations (2012)• Chrome/V8• Firefox/SpiderMonkey• IE10/Chakra• Safari/SquirrelFish (Webkit browsers)• Opera/Carakan
  9. 9. JS Engine Performance (2011) – running JSLint 3 2.5 2milliseconds 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. 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. 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. 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…
  13. 13. …What about Code?….
  14. 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. 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. 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. 17. Objects, Functions• Function • Method • Class • Constructor • Module • Object
  18. 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. 19. Objects, Functions• Function - A function declaration can be called before its declaration. // will work foo(); function func(){ // code... } // wont work - hoisting! func(); var func = function(){ // code }
  20. 20. Objects, Functions• Function - A function declaration can be called before its declaration. // will work foo(); function func(){ // code... } // wont work - hoisting! func(); var func = function(){ // code } …Why?….
  21. 21. Objects, Functions• Function • hoisting of variables. (function(){ function func(){ // code } func() }) (function(){ var func = undefined; func() // returns undefined func = function(){ // code } })
  22. 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. 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. 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. 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. 26. Objects, Functions• Everythings 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. 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. 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. 29. Operators• Arithmetic * - + / %• Comparison === !== < > <= >=• Logical && || !• Bitwise & | ^ >> >>> <<
  30. 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. 31. this
  32. 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. 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. 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. 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. 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. 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. 38. Primitives• Numbers• Boolean• String• Undefined• Null
  39. 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. 40. Primitives• Numbers (continued) • Max number (253) 9007199254740992 • Methods • toExplonential() • toFixed() • toLocalString() • toPrecision() • toString() • valueOf()
  41. 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. 42. Primitives• Math object • abs() • floor() • sqrt() • acos() • log() • tan() • asin() • max() • atan() • min() • atab2() • pow() • ceil() • random() • cos() • round() • exp() • sin()
  43. 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. 44. Primitives Boolean True or False 1 or 0
  45. 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. 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. 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. 48. Primitives• String methods • charAt() • slice() • charCodeAt() • split() • concat() • substr() • indexOf() • substring() • lastIndexOf() • toLocalLowerCase() • localCompare() • toLocalUpperCase() • match() • toLowerCase() • replace() • toString() • search() • toUpperCase()
  49. 49. Primitives• String methods (…continued) • trim() ES5 • trimLeft() ES5 • trimRight() ES5
  50. 50. Primitives• String methods (…continued) • trim() ES5 • trimLeft() ES5 • trimRight() ES5…What about ES3?….
  51. 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. 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. 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. 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. 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. 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. 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. 58. Special Type of Object• Date • …..too many methods to list! (48) • Y2K compliant – was not initially
  59. 59. …Watch out!….Gotchers…
  60. 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. 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. 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. 63. Watch out!• Immediately invocable function expression function(){ // code }(); // syntax error! cant be immediately invoked (function(){ // code }());• Infinity/-Infinity • 1/0 === Infinity • -1/0 === -Infinity • Test for Infinity/-Infinity use isFinite()
  64. 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. 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. 66. Until next time…Twitter: #quintonsGithub id: quintons

×