JavaScript - Like a Box of Chocolates - jsDay

5,568 views

Published on

This presentation aims to give you information about the JavaScript language itself; pros, cons and pitfalls. It will cover the basics and then go into objects, scope, closure and some performance bits.

Published in: Technology
0 Comments
3 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
5,568
On SlideShare
0
From Embeds
0
Number of Embeds
91
Actions
Shares
0
Downloads
45
Comments
0
Likes
3
Embeds 0
No embeds

No notes for slide

JavaScript - Like a Box of Chocolates - jsDay

  1. JavaScriptLike a Box of Chocolates
  2. @robertnymanhttp://robertnyman.com
  3. “Are you telling me that I can’t get awayanymore without getting deeply into Javascript?” - Developer
  4. “That is a disaster for me! I have made a careerout of actively avoiding Javascript.” - Developer
  5. “If I cant continue to ignore Javascript, then youmay as well amputate one of my limbs.” - Developer
  6. // Various "false" valuesvar nullVal = null;var undefinedVal = undefined;var zeroVal = 0;var falseVal = false;var emptyString = "";// All would equal false in an if-clauseif (emptyString) { // Would never go in here}
  7. “Coercion is the practice of forcing another partyto behave in an involuntary manner” - Wikipedia
  8. rci on c oe// Equality Ty peif (7 == "7") { // true}// Identityif (7 === "7") { // false}
  9. // Type coercionvar sum = "5" + 6 + 7; // 567
  10. // Prevent type coercionvar sum = parseInt("5", 10) + 6 + 7; // 18
  11. // Self-invoking functions(function () { var investment = "Lieutenant Dan got meinvested in some kind of fruit company.";})();
  12. // Using argumentsfunction friends (friend1, friend2) { return friend1 + " & " + friend2;}// Lieutenant Dan & Bubbafriends("Lieutenant Dan", "Bubba");// Lieutenant Dan & undefinedfriends("Lieutenant Dan");
  13. // Using the arguments collectionfunction friends () { var allFriends = []; for (var i=0, il=arguments.length; i<il; i++) { allFriends.push(arguments[i]); }; return allFriends.join(" & ");}// Lieutenant Dan & Bubbafriends("Lieutenant Dan", "Bubba");// Lieutenant Danfriends("Lieutenant Dan");
  14. // Object declarationfunction Forrest () { this.firstName = "Forrest"; this.lastName = "Gump";}var forrest = new Forrest();
  15. // Object declaration, literal stylevar forrest = { firstName : "Forrest", lastName : "Gump"};
  16. // Iterating over propertiesfor (var item in forrest) { console.log(item + ": " + forrest[item]);}
  17. // Object declarationvar forrest = { firstName : "Forrest"};// Safe check for propertyif ("firstName" in forrest) { console.log(forrest.firstName);}
  18. // Object declarationfunction ForrestAsChild { this.firstName = "Forrest";};// Method set via prototypeForrestAsChild.prototype.runsFast = function () { return true;};
  19. // Object declarationfunction ForrestAsGrownup { this.joinsArmy = true;};// Prototype for new objectForrestAsGrownup.prototype = new ForrestAsChild;// Method set via prototypeForrestAsGrownup.prototype.ruinsBathrobe = function () { return "I think I ruined your roommates bathrobe";};
  20. // Create an instancevar forrest = new ForrestAsGrownup();// Returns "I think I ruined your roommates bathrobe"forrest.ruinsBathrobe();// Returns true - from ForrestAsChildforrest.runsFast();// Failsforrest.codesJavaScript();
  21. forrest instanceForrestAsGrownupForrestAsChildObject
  22. // Extending core JavaScript objectsif (typeof Array.prototype.push === "undefined") { Array.prototype.push = function () { for (var i=0, il=arguments.length; i<il; i++) { this[this.length] = arguments[i]; }; return this; }}var locations = ["Vietnam"];locations.push("China", "White House");// locations = ["Vietnam", "China", "White House"];
  23. // Scope - global or local// Globalvar quote = "I had run for 3 years, 2 months,14 days, and 16 hours."function () { // Local var pantherParty = "Im sorry I had tofight in the middle of your Black Pantherparty."; // Global question = "And so, you just ran?";}
  24. // Globalfunction meetingJFK () { var JFKQuestion = "Congratulations, how doyou feel?"; // Local function forrestReply () { return "I gotta pee."; } return forrestReply();}meetingJFK(); // I gotta peeforrestReply(); // Error: not accessible
  25. // Controlling scopefunction whoAmI () { return this.nodeName;}whoAmI(); // undefinedwhoAmI.call(document, "Hello"); // #documentwhoAmI.apply(document.body, ["Hello", "Greetings?"]); // BODY
  26. // closuresfunction happens (what) { return function (verb) { return what + " " + verb; }}var action = happens("Shit");action("happens"); // Shit happens
  27. // closuresfunction happens (what) { return function (verb) { return what + " " + verb; }}var action = happens("Shit");// Breaking it downvar action = function (verb) { return "Shit" + " " + verb;};
  28. var link;for (var i=0; i<3; i++) { link = document.createElement("a"); link.innerHTML = "Link " + i; link.onclick = function () { alert("I am link " + i); }; document.body.appendChild(link);};
  29. var link;for (var i=0; i<3; i++) { link = document.createElement("a"); link.innerHTML = "Link " + i; link.onclick = function (index) { return function () { alert("I am link " + index); }; }(i); document.body.appendChild(link);};
  30. // Yahoo! JavaScript Module Patternvar forrest = function () { var firstName = "Forrest"; return { getFirstName : function () { return firstName; } };}();// Returns "Forrest"forrest.getFirstName();
  31. // Yahoo! JavaScript Module Patternvar forrest = function () { var firstName = "Forrest", getFirstName = function () { return firstName; }; return { getFirstName : getFirstName };}();// Returns "Forrest"forrest.getFirstName();
  32. // Namespacingvar Movie = {};// Yahoo! JavaScript Module PatternMovie.forrest = function () { var lastName = "Gump"; return { firstName : "Forrest", getFirstName : function () { return this.firstName; } };}();
  33. // Yahoo! JavaScript Module PatternMovie.forrest = function () { var lastName = "Gump"; return { firstName : "Forrest", getFirstName : function () { return this.firstName; } };}();// Yahoo! JavaScript Module PatternMovie.lieutenantDan = function () { var lastName = "Taylor"; return { firstName : "Dan", getFullName : function () { return Movie.forrest.getFirstName.call(this) + " " + lastName; } };}();Movie.lieutenantDan.getFullName();
  34. // Minimize DOM accessdocument.getElementById("container").className = "js-enabled";document.getElementById("container").innerHTML += "Hello Verona";document.getElementById("container").innerHTML += "Tell me how you doin!";document.getElementById("container").innerHTML += "Lovely to be here...";document.getElementById("container").innerHTML += "...at a World Heritage Site";
  35. // Minimize DOM accessvar container = document.getElementById("container"), content = "Hello Verona";container.className = "js-enabled";content += "Tell me how you doin!";content += "Lovely to be here...";content += "...at a World Heritage Site";container.innerHTML = content;
  36. // Looping, variables and array lookupsfunction forrestForm () { var allParagraphs = document.getElementsByTagName("p"); for (var i=0; i<allParagraphs.length; i++) { var link = document.createElement("a"); link.href = "http://en.wikipedia.org/wiki/Forrest_Gump"; link.title = "Read about Forrest Gump at Wikipedia"; link.innerHTML = "Forrest Gump"; allParagraphs[i].className = "Forrested"; allParagraphs[i].appendChild(link); }}
  37. // Looping, variables and array lookupsfunction forrestForm () { var allParagraphs = document.getElementsByTagName("p"); for (var i=0, l=allParagraphs.length, link, paragraph; i<l; i++) { link = document.createElement("a"); link.href = "http://en.wikipedia.org/wiki/Forrest_Gump"; link.title = "Read about Forrest Gump at Wikipedia"; link.innerHTML = "Forrest Gump"; paragraph = allParagraphs[i]; paragraph.className = "Forrested"; paragraph.appendChild(link); }}
  38. // Variable declarationfunction richAndStupid () { var rich = "And cause I was a gazillionaire, Icut that grass for free.", stupid = "Stupid is as stupid does.";}
  39. if (!("a" in window)) { var a = 1;}alert(a); // undefined
  40. function value () { return 1;}var value;alert(typeof value); // function
  41. function value () { return 1;}var value = 3;alert(typeof value); // number
  42. // Semicolon insertionreturnreturn; // Semicolon insertion{ // Considered an empty block javascript : "Fantastic!"}; // Semicolon insertion, dummy line
  43. type of NaN // "number"
  44. 3.toString(); // Error3..toString(); // "3"
  45. var number = 5, check = { number: 10, getNum: function () { var number = 20; setTimeout(function () { alert(this.number); }, 10); } };check.getNum(); // 5
  46. JSLint
  47. http://chrome.angrybirds.com/
  48. Robert Nyman http://robertnyman.com/speaking/ Twitter: @robertnymanPictures:Chocolate: http://10000likes.blogspot.com/2010_11_01_archive.html Seinfeld: http://www.cartoonstock.com/directory/f/false_identity.aspRobocop: http://www.meh.ro/2010/04/01/murphy-as-robocop/ Forcing: http://www.pollsb.com/polls/p2116218-forcing_guy_look_computer_screenBruce Willis: http://www.starsjournal.com/3192/bruce-willis-is-being-sued-for-4-million-dollars.html Play with yourself: http://verydemotivational.memebase.com/2008/06/07/funny-demotivational-posters-masturbation/Swedish flag: http://scrapetv.com/News/News%20Pages/usa/Images/swedish-flag.jpg Overloading: http://theshadowhive.blogspot.com/2010/04/mutating-chaos-gene.htmlVerona flag: http://upload.wikimedia.org/wikipedia/commons/thumb/d/dc/Flag_of_Verona.svg/568px- David Hasselhof: http://www.wimereuxwobblers.co.uk/?page_id=6Flag_of_Verona.svg.png Pamela Anderson: http://www.dailyheadlineblog.com/television/pamela-andersons-red-swimsuit-up-for-auction/Swedish woman/flag: http://www.olssonfoto.se/JAlbum/SGP%202008%20Ullevi/slides/Svenska%20flaggan.html Inheritance: http://www.uniquities.co.uk/acatalog/Get_your_GEEK_on.htmlEuro Coin: http://accidentaldong.blogspot.com/2009/10/euro-uh-oh.html Extensible (dachshund): http://dog-breeds.findthebest.com/compare/16-55/Beagle-vs-DachshundMost popular language: http://odetocode.com/Blogs/scott/archive/2009/03/18/signs-that-your-javascript-skills- Tiger Woods: http://blogs.bigadda.com/pal4868546/2010/01/need-updating.aspx Pollution: http://www.fishingfury.com/tags/pollution/Sunrise: http://www.manywallpapers.com/space-wallpapers/earth/sunrise-from-space.html Closure: http://today.msnbc.msn.com/id/4760120Astronaut: http://martianchronicles.wordpress.com/2009/01/23/carnival-of-space-87/ Steve Ballmer: http://www.businessinsider.com/microsoft-completely-rebooted-its-mobile-strategy-yesterday-heres-Netscape 2: http://blog.explorelearning.com/2005/12/index.html what-you-missed-2010-2Internet Explorer 3: http://www.guidebookgallery.org/screenshots/browser Crockford: http://gemsres.com/story/nov07/468365/Crockford_New_4681.jpgGandalf: http://web.mit.edu/kayla/Public/Backgrounds/LOTR%20Gandalf%204.JPG Name: http://blog.usa.gov/roller/govgab/tags/namesNow: http://www.chronicbabe.com/articles/801/ Space: http://gucken.deviantart.com/art/Sunrise-in-Space-56420137Axe: http://bestgamewallpapers.com/a3-the-age-of-sovereign/axe Fail better: http://ozguralaz.posterous.com/ever-tried-ever-failed-no-mattMoney: http://logisticsmonster.com/2010/01/12/the-fed-earns-record-profit-loaning-our-money-to-us/joker- Hoist: http://www.gantry-crane.org/category/hoist/burning-money-in-tdk-3/ Mila & Macaulay: http://uk.eonline.com/uberblog/b61889_mila_macaulay_home_alone.htmlHappy: http://www.petetheplanner.com/blog/2011/03/08/the-cat-poo-story/ Love: http://hyderabadaseels.webs.com/Fast: http://www.curing-premature-ejaculation.com/Forrest Gump: http://wallpaper-s.org/36__Forrest_Gump,_1994,_Tom_Hanks,_Robin_Wright_Penn.htm
  49. http://joind.in/talk/view/3363

×