Javascript The Good Parts v2

  • 4,569 views
Uploaded on

Second iteration of my javascript talk. …

Second iteration of my javascript talk.
Presented at PHP Day Italia 2009 on May 15th.
Slides refactored, cut down code examples and added some content about js abstractions and ecmascript 3.1.

See http://federico.galassi.net/2009/05/17/javascript-the-good-parts-talk/

Follow me on Twitter!
https://twitter.com/federicogalassi

More in: Technology
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
No Downloads

Views

Total Views
4,569
On Slideshare
0
From Embeds
0
Number of Embeds
3

Actions

Shares
Downloads
282
Comments
0
Likes
13

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

  • 1. Javascript The Good Parts Federico Galassi federico.galassi@gmail.com http://federico.galassi.net 1
  • 2. Why Javascript ‣ The language of the Web ‣ A nice, elegant, expressive language 2
  • 3. Javascript: really a good language? ‣ A nice, elegant, expressive language... ‣ What?? 3
  • 4. Javascript perceived as a toy language ‣ Good for web pages ‣ Bad for “serious” programming ‣ large projects ‣ maintainable code 4
  • 5. Javascript is a toy language? Bullshit!! ‣ Stanford University CS 242 “Programming Languages” 2008 ‣ Mozilla Corporation ‣ Firefox ‣ Many more... 5
  • 6. Javascript is not toy language...So what? ‣ The Most Misunderstood language ever ‣ Different from mainstream ‣ Design mistakes ‣ Traditionally runs in the browser 6
  • 7. Javascript is different: not your choice ‣ Not the language of your choice ‣ You already know other good languages ‣ It’s “easy”, no need to learn ‣ Copy&Paste Oriented Programming != 7
  • 8. Javascript is different: an exotic language ‣ Familiar syntax from Java/C ‣ Pretty exotic foundations ‣ Objects from Self ‣ Functions from Scheme if (x < 1) { x++; } 8
  • 9. Javascript has design mistakes ‣ Short lab time ‣ hacked in one week in may 1995 ‣ in Netscape 2 by the end of the year ‣ Too fast adoption ‣ web boom ‣ Controversial goals ‣ “easy” for non programmers ‣ must look like java Brendan Eich Creator of Javascript ‣ No fixes since 1999 ™ Mozilla CTO 9
  • 10. Javascript usually runs in the browser ‣ Inconsistent implementations ‣ poor specifications ‣ Depends on DOM for I/O ‣ and it sucks! ‣ Lack of common features ‣ file system access ‣ sockets ‣ “require” ‣ No standard libraries 10
  • 11. Javascript: Abstractions ‣ The Blooming of Abstractions 11
  • 12. Javascript: Abstractions fix it ‣ Fix the language ‣ Add events portably ‣ Select DOM elements easily YAHOO.util.Event.addListener(quot;elementidquot;, quot;clickquot;, fnCallback); $(quot;.myclassquot;) 12
  • 13. Javascript: Abstractions rewrite it ‣ Rewrite the language ‣ Declare a “classical” class var Person = new Class({ initialize: function(name){ this.name = name; }, greet: function(){ alert(quot;hi, i am quot; + this.name); } }); 13
  • 14. Javascript: Abstractions ignore it ‣ Language?? ‣ It’s a Virtual Machine! public class StockWatcher implements EntryPoint { private Button addStockButton = new Button(quot;Addquot;); public void onModuleLoad() { // Listen for mouse events on the Add button. addStockButton.addClickHandler(new ClickHandler() { public void onClick(ClickEvent event) { addStock(); } }); } 14
  • 15. Javascript: Abstractions...beware ‣ Abstractions are useful yet... ‣ All non-trivial abstractions, to some degree, are leaky. ‣ Knowledge is always good 15
  • 16. Javascript rules as it is! ‣ Imperative ‣ Functional ‣ Object Oriented ‣ Simple ‣ Winner by natural selection ‣ ...where java failed. Dachshund Evolution 16
  • 17. Javascript the different good parts: Functions 1 ‣ First Class Functions ‣ are objects ‣ can be created at runtime ‣ can be stored in variables ‣ can be created as anonymous literals // Creation with literal // Invocation var hello = function(name) { hello; // function() return quot;hello quot; + name; hello(quot;worldquot;); // quot;hello worldquot; }; 17
  • 18. Javascript the different good parts: Functions 2 ‣ First Class Functions ‣ can be passed as parameters to functions ‣ can be returned by functions // Passed as parameter and invoked // Returned by a function var hey = function() { print quot;heyquot; }; var makeHey = function() { var twice = function(func) { return function() { func(); func(); return quot;hey”; }; } twice(hey); // prints quot;heyheyquot; }; var hey2 = makeHey(); hey2(); // quot;heyquot; 18
  • 19. Javascript the different good parts: Functions and Scope ‣ Scopes Global g = 1 b = 2 ‣ Global function outer() { Function function inner() { ‣ Function var i = 4; ‣ No block-level } o = 3 var o = 3; } i = 4 var g = 1; if (true) { var b = 2; } 19
  • 20. Javascript the different good parts: Functions and Scope Chain ‣ Scope Chain Global g = 1 b = 2 function outer() { Function ‣ Each scope “inherits” from function inner() { var i = 4; the “previous” } o = 3 one var o = 3; } i = 4 var g = 1; if (true) { var b = 2; } Scope Chain 20
  • 21. Javascript the different good parts: Functions as Closures ‣ Closure: Global g = 1 Functions function outer() { Function var g = 3; “remember” return function() { their scope return g; g = 3 chain } } var g = 1 var inner = outer(); inner(); // returns 3 Scope Chain 21
  • 22. Javascript the different good parts: Objects 1 ‣ Containers of key/value pairs ‣ keys are strings ‣ values are anything // Creation with literal book var book = { quot;titlequot; quot;Javascriptquot; title: quot;Javascriptquot;, quot;pagesquot; 240 pages: 240, quot;authorquot; - author: { name: quot;Federicoquot;, surname: quot;Galassiquot; } quot;namequot; quot;Federicoquot; } quot;surnamequot; quot;Galassiquot; 22
  • 23. Javascript the different good parts: Objects 2 ‣ Objects are dynamic ‣ Properties can be added and removed at runtime ‣ No class constraints // Get a property book[quot;titlequot;] // returns quot;Javascriptquot; book.title // same as book[quot;titlequot;] book.propertyNotThere // returns undefined // Set or update a property book.cover = quot;butterfly.jpgquot; book.title = quot;Javascript the good partsquot; // Delete a property delete book.title // now book.title is undefined 23
  • 24. Javascript the different good parts: Objects Methods ‣ Methods are function valued book properties quot;titlequot; quot;Javascriptquot; quot;pagesquot; 240 ‣ Inside methods quot;readquot; - this is bound to Method object “on the left” function() { var action = quot;Reading quot;; return action + this.title; book.read = function() { } var action = quot;Reading quot;; return action + this.title; Scope } action = quot;Reading quot; this = book.read(); // returns quot;Reading Javascriptquot; 24
  • 25. Javascript the different good parts: Objects Prototype ‣ Every object can be linked to another object through the special “prototype” property ‣ If a property does not exist in the object, request is delegated to its prototype another_point var point = { quot;xquot; 20 x: 10, __proto__ - y: 10 }; var another_point = Object.create(point); point another_point.x = 20; quot;xquot; 10 quot;yquot; 10 another_point.x; // returns 20 __proto__ - another_point.y; // returns 10 (delegated) 25
  • 26. Javascript the different good parts: Objects Prototype and Methods ‣ Delegation works for methods too ‣ this is always bound to the “first object” // returns 20 * 10 = 200 another_rect another_rect.area(); quot;widthquot; 20 __proto__ - Scope this = Prototype rect Method quot;widthquot; 10 function() { quot;heightquot; 10 return this.width * quot;areaquot; - this.height; __proto__ - } 26
  • 27. Javascript the different good parts: Objects Prototype Chain ‣ Properties are resolved by following the Prototype Chain ‣ Prototype Chains always ends with Object ‣ Beyond there’s undefined first.asdasdasd; // quot;asdasdasdquot; not in first // first, second, last __proto__ - // quot;asdasdasdquot; not in {} // returns undefined Pr oluti Re op s second er on first.hasOwnProperty ty __proto__ - // returns function() ... Object last __proto__ - 27
  • 28. Javascript the different good parts: Objects Prototypal Inheritance 1 ‣ Prototypes are javascript way to share ‣ Data ‣ Behavior 28
  • 29. Javascript the different good parts: Objects Prototypal Inheritance 2 ‣ Prototypal Inheritance ‣ Vs Classical Inheritance ‣ Simpler ‣ No classes and objects, only objects ‣ Easier ‣ Work by examples, not abstractions ‣ Powerful !! ‣ Can simulate classical ‣ Reverse not true ‣ Shhhh, Don’t tell anyone ‣ Easier to write spaghetti code 29
  • 30. Javascript the different good parts: Objects Prototypal Inheritance 3 ‣ Ok, I cheated ‣ __proto__ available in mozilla only ‣ Object.create coming in next revision of language ‣ Javascript is schizophrenic ‣ Prototypal nature ‣ Wannabe classical 30
  • 31. Javascript the different good parts: Object Constructor 1 ‣ Constructor Functions ‣ Function is a class constructor ‣ Function prototype is class behavior ‣ new makes new objects ‣ Why? function Rectangle(w, h) { ‣ feels classical this.w = w; this.h = h; ‣ feels familiar } Rectangle.prototype.higher = function() { this.h += 1 }; var rect = new Rectangle(5,10); 31
  • 32. Javascript the different good parts: Object Constructor 2 ‣ Worst of both worlds ‣ Unnecessarily complicated ‣ Hide prototypal nature ‣ Weird for classical programmers 32
  • 33. Javascript the different good parts: Objects Constructor Functions Fix ‣ Fortunately there’s a Quick Fix // create an object with a given prototype if (typeof Object.create !== 'function') { Object.create = function (o) { var F = function() {}; F.prototype = o; return new F(); }; } var siamese = Object.create(cat); 33
  • 34. Javascript the different good parts: Arrays ‣ No real arrays in javascript ‣ They’re objects in disguise ‣ special props and methods ‣ Cool literal syntax // array literal var numbers = [1, 2, 3]; // nice methods numbers.push(4); // now [1, 2, 3, 4] // an object indeed numbers.dog = 'pretty'; 34
  • 35. Javascript the different good parts: Functional Programming ‣ Iterators ‣ Callbacks ‣ Module Pattern ‣ Memoization 35
  • 36. Javascript the different good parts: Functional Programming Iterators ‣ Take control of loops ‣ Reduce accidental complexity 36
  • 37. Javascript the different good parts: Iterators Example 1 // iterate on a collection function each(arr, func) { for (var i=0; i<arr.length; i++) { func(arr[i]); } } var ten = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; each(ten, function(i) { print i; }); // prints 12345678910 37
  • 38. Javascript the different good parts: Iterators Example 2 // maps a collection to a new one function map(arr, func) { var result = []; each(arr, function(i) { result.push(func(i)); }); return result; } var ten = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; map(ten, function(i) { return i * i; }); // returns [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] 38
  • 39. Javascript the different good parts: Iterators Example 3 // filter elements of a collection function filter(arr, func) { var result = []; each(arr, function(i) { if (func(i)) { result.push(i); } }); return result; } var ten = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; filter(ten, function(i) { return i % 2 === 0; }); // returns [2, 4, 6, 8, 10] 39
  • 40. Javascript the different good parts: Iterators Example 4 // compute a single value from a collection function reduce(arr, func, start) { var result = start; each(arr, function(i) { result = func(i, result); }); return result; } var ten = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; reduce(ten, function(i, sum) { return i + sum; }, 0); // returns 55 40
  • 41. Javascript the different good parts: Iterators Example 5 // Composability // square elements, then pick even ones, then sum reduce( filter( map(ten, function(i) { return i * i; } ), function(i) { return i % 2 === 0; } ), function(i, sum) { return i + sum; }, 0 ); 41
  • 42. Javascript the different good parts: Iterators Example 6 // Composability but easy to read var square = function(arr) { return map(arr, function(i) { return i * 2; }); } var even = function(arr) { return filter(arr, function(i) { return i % 2 === 0; }); } var sum = function(arr) { return reduce(arr, function(i, total) { return i + total; }, 0); } sum(even(square(ten))); 42
  • 43. Javascript the different good parts: Functional Programming Callbacks ‣ Manage asynchronous communication ‣ Hide complexity 43
  • 44. Javascript the different good parts: Callbacks Example 1 // Synchronous request var response = get(quot;http://www.google.comquot;); display(response); // Asynchronous with callback get(quot;http://www.google.comquot;, function(response) { display(response); }); 44
  • 45. Javascript the different good parts: Callbacks Example 2 // explicit complexity var response = get(quot;http://www.google.comquot;); if (response.completed) { if (response.httpCode === quot;200quot;) { display(response); } else { // http error } } else { // network error } 45
  • 46. Javascript the different good parts: Callbacks Example 3 // complexity hidden in the client code var response = get(quot;http://www.google.comquot;); if (success(response)) { display(response); } else { // error } // complexity hidden away get(quot;http://www.google.comquot;, { success: function(response) { display(response); } }); 46
  • 47. Javascript the different good parts: Functional Programming Module Pattern ‣ Hide state and behavior 47
  • 48. Javascript the different good parts: Module Pattern Example 1 var numbers = [quot;zeroquot;, quot;onequot;, quot;twoquot;, quot;threequot;, ...]; // GLOBAL BAD var numberToString = function(num) { return numbers[num]; } var numberToString = function(num) { // LOCAL SLOW var numbers = [quot;zeroquot;, quot;onequot;, quot;twoquot;, quot;threequot;, ...]; return numbers[num]; } var numberToString = function() { // PRIVATE AND FAST var numbers = [quot;zeroquot;, quot;onequot;, quot;twoquot;, quot;threequot;, ...]; return function(num) { return numbers[num]; } }(); 48
  • 49. Javascript the different good parts: Functional Programming Memoization ‣ Cache computation ‣ Speed up execution 49
  • 50. Javascript the different good parts: Memoization Example 1 // get pixels. maybe millions of them var pixels = getImagePixels(quot;image.jpgquot;); var getColor = function(pixel) { // ... computation on RGB values ... returns quot;blackquot;; // or quot;whitequot; or quot;greenquot; etc... } // find the color pixels.each(function(pixel) { var color = getColor(pixel); // store result }); 50
  • 51. Javascript the different good parts: Memoization Example 2 // wasted computation on already calculated pixels // cache it... var getColorCache = function(func) { var cache; // setup cache ... return function(pixel) { if (cache.missing(pixel)) { cache.store(pixel, func(pixel)); } return cache.get(pixel); } }(getColor); 51
  • 52. Javascript the bad parts ‣ The features you should definitely avoid 52
  • 53. Javascript the bad parts 1 ‣ Global variables ‣ Semicolon insertion // Good, returns { ok: true } // Very bad, returns undefined return { return ok: true { } ok: true } ‣ Reserved words // Good // Very bad, error book[quot;classquot;]; book.class; var book = { var book = { quot;classquot;: quot;bookquot; class: quot;bookquot; } } 53
  • 54. Javascript the bad parts 2 ‣ Unicode ‣ typeof // Not useful, returns quot;objectquot; typeof array; // Wrong, returns quot;objectquot; typeof null; // Inconsistent, returns quot;functionquot; or quot;objectquot; typeof /a/; ‣ parseInt // Good, returns 8 // Wrong, returns 0 parseInt(quot;08quot;, 10); parseInt(quot;08quot;); 54
  • 55. Javascript the bad parts 3 ‣+ ‣ Floating Point 0.2 + 0.1 === 0.3 // false ‣ Phony Arrays arguments.join // returns undefined ‣ Falsy values if (book.name == null) { ... // 2 errors, works by coincidence ‣ == type coercion '' == '0' // false false == undefined // false 0 == '' // true false == null // false 0 == '0' // true null == undefined // true 55
  • 56. Javascript the bad parts 4 ‣ Objects are not hashes var cache; var word = getWord(); // returns quot;constructorquot; if (word in cache) { // ops, true ‣ Deep for..in // safe way for (var i in list) { if (list.hasOwnProperty(i)) { // do something } } ‣ Extending native prototypes kill kittens ‣ new ‣ forgetting new makes global variables! 56
  • 57. Javascript the bad parts: ES3.1 Salvation ‣ ECMAScript 3.1 to Save Us ‣ Object.create built-in ‣ Properties enumerable/writable/configurable ‣ JSON built-in ‣ Properties accessors ‣ Security ‣ strict mode ‣ object “lock down” ‣ Coming Soon On Your Browser! 57
  • 58. Credits ‣ Thank to Douglas Crockford and his book ‣ He knows the way 58