SlideShare a Scribd company logo
JavaScript
Like a Box of Chocolates
JavaScript - Like a Box of Chocolates - jsDay
JavaScript - Like a Box of Chocolates - jsDay
@robertnyman

http://robertnyman.com
JavaScript - Like a Box of Chocolates - jsDay
JavaScript - Like a Box of Chocolates - jsDay
JavaScript - Like a Box of Chocolates - jsDay
JavaScript - Like a Box of Chocolates - jsDay
JavaScript - Like a Box of Chocolates - jsDay
JavaScript - Like a Box of Chocolates - jsDay
JavaScript - Like a Box of Chocolates - jsDay
“Are you telling me that I can’t get away
anymore without getting deeply into Javascript?”

                                         - Developer
“That is a disaster for me! I have made a career
out of actively avoiding Javascript.”

                                         - Developer
“If I cant continue to ignore Javascript, then you
may as well amputate one of my limbs.”

                                           - Developer
JavaScript - Like a Box of Chocolates - jsDay
JavaScript - Like a Box of Chocolates - jsDay
JavaScript - Like a Box of Chocolates - jsDay
JavaScript - Like a Box of Chocolates - jsDay
JavaScript - Like a Box of Chocolates - jsDay
JavaScript - Like a Box of Chocolates - jsDay
// Various "false" values
var nullVal = null;
var undefinedVal = undefined;
var zeroVal = 0;
var falseVal = false;
var emptyString = "";

// All would equal false in an if-clause
if (emptyString) {
    // Would never go in here
}
JavaScript - Like a Box of Chocolates - jsDay
“Coercion is the practice of forcing another party
to behave in an involuntary manner”

                                          - Wikipedia
rci on
                           c oe
// Equality
                   Ty pe
if (7 == "7") {
    // true
}

// Identity
if (7 === "7") {
    // false
}
// Type coercion
var sum = "5" + 6 + 7; // 567
// Prevent type coercion
var sum = parseInt("5", 10) + 6 + 7; // 18
JavaScript - Like a Box of Chocolates - jsDay
// Self-invoking functions
(function () {
    var investment = "Lieutenant Dan got me
invested in some kind of fruit company.";
})();
JavaScript - Like a Box of Chocolates - jsDay
// Using arguments
function friends (friend1, friend2) {
    return friend1 + " & " + friend2;
}

// Lieutenant Dan & Bubba
friends("Lieutenant Dan", "Bubba");

// Lieutenant Dan & undefined
friends("Lieutenant Dan");
// Using the arguments collection
function friends () {
    var allFriends = [];
    for (var i=0, il=arguments.length; i<il; i++) {
        allFriends.push(arguments[i]);
    };
    return allFriends.join(" & ");
}

// Lieutenant Dan & Bubba
friends("Lieutenant Dan", "Bubba");

// Lieutenant Dan
friends("Lieutenant Dan");
JavaScript - Like a Box of Chocolates - jsDay
// Object declaration
function Forrest () {
    this.firstName = "Forrest";
    this.lastName = "Gump";
}

var forrest = new Forrest();
// Object declaration, literal style
var forrest = {
    firstName : "Forrest",
    lastName : "Gump"
};
// Iterating over properties
for (var item in forrest) {
     console.log(item + ": " + forrest[item]);
}
// Object declaration
var forrest = {
    firstName : "Forrest"
};

// Safe check for property
if ("firstName" in forrest) {
    console.log(forrest.firstName);
}
JavaScript - Like a Box of Chocolates - jsDay
// Object declaration
function ForrestAsChild {
    this.firstName = "Forrest";
};

// Method set via prototype
ForrestAsChild.prototype.runsFast = function () {
    return true;
};
// Object declaration
function ForrestAsGrownup {
    this.joinsArmy = true;
};

// Prototype for new object
ForrestAsGrownup.prototype = new ForrestAsChild;

// Method set via prototype
ForrestAsGrownup.prototype.ruinsBathrobe = function () {
    return "I think I ruined your roommate's bathrobe";
};
// Create an instance
var forrest = new ForrestAsGrownup();

// Returns "I think I ruined your roommate's bathrobe"
forrest.ruinsBathrobe();

// Returns true - from ForrestAsChild
forrest.runsFast();

// Fails
forrest.codesJavaScript();
forrest instance

ForrestAsGrownup

ForrestAsChild

Object
JavaScript - Like a Box of Chocolates - jsDay
// Extending core JavaScript objects
if (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"];
JavaScript - Like a Box of Chocolates - jsDay
// Scope - global or local

// Global
var quote = "I had run for 3 years, 2 months,
14 days, and 16 hours."

function () {
    // Local
    var pantherParty = "I'm sorry I had to
fight in the middle of your Black Panther
party.";

    // Global
    question = "And so, you just ran?";
}
// Global
function meetingJFK () {
    var JFKQuestion = "Congratulations, how do
you feel?";

    // Local
    function forrestReply () {
        return "I gotta pee.";
    }

    return forrestReply();
}

meetingJFK(); // I gotta pee
forrestReply(); // Error: not accessible
// Controlling scope
function whoAmI () {
    return this.nodeName;
}

whoAmI(); // undefined
whoAmI.call(document, "Hello"); // #document
whoAmI.apply(document.body, ["Hello", "Greetings?"]); // BODY
JavaScript - Like a Box of Chocolates - jsDay
JavaScript - Like a Box of Chocolates - jsDay
// closures
function happens (what) {
    return function (verb) {
        return what + " " + verb;
    }
}

var action = happens("Shit");

action("happens"); // Shit happens
JavaScript - Like a Box of Chocolates - jsDay
// closures
function happens (what) {
    return function (verb) {
        return what + " " + verb;
    }
}

var action = happens("Shit");

// Breaking it down
var action = function (verb) {
    return "Shit" + " " + verb;
};
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);
};
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);
};
JavaScript - Like a Box of Chocolates - jsDay
// Yahoo! JavaScript Module Pattern
var forrest = function () {
    var firstName = "Forrest";

       return {
           getFirstName : function () {
                return firstName;
           }
       };
}();

// Returns "Forrest"
forrest.getFirstName();
// Yahoo! JavaScript Module Pattern
var forrest = function () {
    var firstName = "Forrest",
        getFirstName = function () {
            return firstName;
        };

       return {
           getFirstName : getFirstName
       };
}();

// Returns "Forrest"
forrest.getFirstName();
JavaScript - Like a Box of Chocolates - jsDay
// Namespacing
var Movie = {};

// Yahoo! JavaScript Module Pattern
Movie.forrest = function () {
    var lastName = "Gump";

       return {
           firstName : "Forrest",
           getFirstName : function () {
                return this.firstName;
           }
       };
}();
// Yahoo! JavaScript Module Pattern
Movie.forrest = function () {
    var lastName = "Gump";

       return {
           firstName : "Forrest",
           getFirstName : function () {
                return this.firstName;
           }
       };
}();



// Yahoo! JavaScript Module Pattern
Movie.lieutenantDan = function () {
    var lastName = "Taylor";

       return {
           firstName : "Dan",
           getFullName : function () {
                return Movie.forrest.getFirstName.call(this) + " " + lastName;
           }
       };
}();

Movie.lieutenantDan.getFullName();
JavaScript - Like a Box of Chocolates - jsDay
// Minimize DOM access
document.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";
// Minimize DOM access
var 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;
// Looping, variables and array lookups
function 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);
    }
}
// Looping, variables and array lookups
function 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);
    }
}
// Variable declaration
function richAndStupid () {
    var rich = "And cause I was a gazillionaire, I
cut that grass for free.",
        stupid = "Stupid is as stupid does.";
}
JavaScript - Like a Box of Chocolates - jsDay
if (!("a" in window)) {
  var a = 1;
}
alert(a); // undefined
function value () {
    return 1;
}
var value;
alert(typeof value); // function
function value () {
    return 1;
}
var value = 3;
alert(typeof value); // number
// Semicolon insertion
return
return; // Semicolon insertion
{ // Considered an empty block
    javascript : "Fantastic!"
}; // Semicolon insertion, dummy line
type of NaN // "number"
3.toString(); // Error
3..toString(); // "3"
var number = 5,
  check = {
     number: 10,
     getNum: function () {
       var number = 20;
       setTimeout(function () {
         alert(this.number);
       }, 10);
     }
  };
check.getNum(); // 5
JSLint
JavaScript - Like a Box of Chocolates - jsDay
http://chrome.angrybirds.com/
Robert Nyman
                                                              http://robertnyman.com/speaking/

                                                                                Twitter: @robertnyman



Pictures:

Chocolate: http://10000likes.blogspot.com/2010_11_01_archive.html                                               Seinfeld: http://www.cartoonstock.com/directory/f/false_identity.asp
Robocop: http://www.meh.ro/2010/04/01/murphy-as-robocop/                                                        Forcing: http://www.pollsb.com/polls/p2116218-forcing_guy_look_computer_screen
Bruce 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.html
Verona flag: http://upload.wikimedia.org/wikipedia/commons/thumb/d/dc/Flag_of_Verona.svg/568px-                  David Hasselhof: http://www.wimereuxwobblers.co.uk/?page_id=6
Flag_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.html
Euro Coin: http://accidentaldong.blogspot.com/2009/10/euro-uh-oh.html                                           Extensible (dachshund): http://dog-breeds.findthebest.com/compare/16-55/Beagle-vs-Dachshund
Most 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/4760120
Astronaut: 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-2
Internet Explorer 3: http://www.guidebookgallery.org/screenshots/browser                                        Crockford: http://gemsres.com/story/nov07/468365/Crockford_New_4681.jpg
Gandalf: http://web.mit.edu/kayla/Public/Backgrounds/LOTR%20Gandalf%204.JPG                                     Name: http://blog.usa.gov/roller/govgab/tags/names
Now: http://www.chronicbabe.com/articles/801/                                                                   Space: http://gucken.deviantart.com/art/Sunrise-in-Space-56420137
Axe: http://bestgamewallpapers.com/a3-the-age-of-sovereign/axe                                                  Fail better: http://ozguralaz.posterous.com/ever-tried-ever-failed-no-matt
Money: 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.html
Happy: 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
http://joind.in/talk/view/3363
JavaScript - Like a Box of Chocolates - jsDay

More Related Content

PDF
JavaScript - Like a Box of Chocolates
PDF
JavaScript and HTML5 - Brave New World (revised)
KEY
jQuery Anti-Patterns for Performance & Compression
PDF
The Spirit of Testing
PDF
How DRY impacts JavaScript performance // Faster JavaScript execution for the...
PDF
Bologna Developer Zone - About Kotlin
PDF
H3 경쟁력있는 웹앱 개발을 위한 모바일 js 프레임웍
PDF
How to actually use promises - Jakob Mattsson, FishBrain
JavaScript - Like a Box of Chocolates
JavaScript and HTML5 - Brave New World (revised)
jQuery Anti-Patterns for Performance & Compression
The Spirit of Testing
How DRY impacts JavaScript performance // Faster JavaScript execution for the...
Bologna Developer Zone - About Kotlin
H3 경쟁력있는 웹앱 개발을 위한 모바일 js 프레임웍
How to actually use promises - Jakob Mattsson, FishBrain

What's hot (20)

PDF
has("builds")
PDF
dojo.things()
PPT
Memory Leaks In Internet Explorer
PPT
Memory Leaks In Internet Explorer
PDF
Pragmatic JavaScript
KEY
Java & Script ─ 清羽
PDF
Firefox OS learnings & visions, WebAPIs - budapest.mobile
PDF
Clean code
KEY
FizzBuzzではじめるテスト
PDF
ภาษา C
PDF
Ruby Robots
PDF
儲かるドキュメント
PDF
Dario Faggioli - Virtualization in the age of speculative execution HW bugs
PDF
Prototypal inheritance in JavaScript
PDF
Beware sharp tools
PDF
a hands on guide to django
PDF
Using Buildout to Develop and Deploy Python Projects
PDF
Celluloid - Beyond Sidekiq
PDF
Mojolicious
KEY
Dig Deeper/Django C-notes
has("builds")
dojo.things()
Memory Leaks In Internet Explorer
Memory Leaks In Internet Explorer
Pragmatic JavaScript
Java & Script ─ 清羽
Firefox OS learnings & visions, WebAPIs - budapest.mobile
Clean code
FizzBuzzではじめるテスト
ภาษา C
Ruby Robots
儲かるドキュメント
Dario Faggioli - Virtualization in the age of speculative execution HW bugs
Prototypal inheritance in JavaScript
Beware sharp tools
a hands on guide to django
Using Buildout to Develop and Deploy Python Projects
Celluloid - Beyond Sidekiq
Mojolicious
Dig Deeper/Django C-notes
Ad

Similar to JavaScript - Like a Box of Chocolates - jsDay (20)

PDF
JavaScript & HTML5 - Brave New World
KEY
JavaScript Neednt Hurt - JavaBin talk
PPTX
Awesomeness of JavaScript…almost
KEY
PPTX
Java Script basics and DOM
PPTX
Java script
PPT
JavaScript - Programming Languages course
PPT
eXo SEA - JavaScript Introduction Training
PPTX
All of Javascript
PPT
JavaScript Needn't Hurt!
PDF
Java script
PPTX
All of javascript
KEY
JavaScript @ CTK
PPTX
Java script basics
PPT
JavaScript: Ajax & DOM Manipulation
PDF
PDF
PDF
CoffeeScript
ODP
JavaScript and jQuery Fundamentals
JavaScript & HTML5 - Brave New World
JavaScript Neednt Hurt - JavaBin talk
Awesomeness of JavaScript…almost
Java Script basics and DOM
Java script
JavaScript - Programming Languages course
eXo SEA - JavaScript Introduction Training
All of Javascript
JavaScript Needn't Hurt!
Java script
All of javascript
JavaScript @ CTK
Java script basics
JavaScript: Ajax & DOM Manipulation
CoffeeScript
JavaScript and jQuery Fundamentals
Ad

More from Robert Nyman (20)

PDF
Have you tried listening?
PDF
Building for Your Next Billion - Google I/O 2017
PDF
Introduction to Google Daydream
PDF
Predictability for the Web
PDF
The Future of Progressive Web Apps - View Source conference, Berlin 2016
PDF
The Future of the Web - Cold Front conference 2016
PDF
The Future of Progressive Web Apps - Google for Indonesia
PDF
Google tech & products
PDF
Introduction to Progressive Web Apps, Google Developer Summit, Seoul - South ...
PDF
Progressive Web Apps keynote, Google Developer Summit, Tokyo, Japan
PDF
The web - What it has, what it lacks and where it must go - keynote at Riga D...
PDF
The web - What it has, what it lacks and where it must go - Bulgaria Web Summ...
PDF
The web - What it has, what it lacks and where it must go - Istanbul
PDF
The web - What it has, what it lacks and where it must go
PDF
Google, the future and possibilities
PDF
Developer Relations in the Nordics
PDF
What is Developer Relations?
PDF
Android TV Introduction - Stockholm Android TV meetup
PDF
New improvements for web developers - frontend.fi, Helsinki
PDF
Mobile phone trends, user data & developer climate - frontend.fi, Helsinki
Have you tried listening?
Building for Your Next Billion - Google I/O 2017
Introduction to Google Daydream
Predictability for the Web
The Future of Progressive Web Apps - View Source conference, Berlin 2016
The Future of the Web - Cold Front conference 2016
The Future of Progressive Web Apps - Google for Indonesia
Google tech & products
Introduction to Progressive Web Apps, Google Developer Summit, Seoul - South ...
Progressive Web Apps keynote, Google Developer Summit, Tokyo, Japan
The web - What it has, what it lacks and where it must go - keynote at Riga D...
The web - What it has, what it lacks and where it must go - Bulgaria Web Summ...
The web - What it has, what it lacks and where it must go - Istanbul
The web - What it has, what it lacks and where it must go
Google, the future and possibilities
Developer Relations in the Nordics
What is Developer Relations?
Android TV Introduction - Stockholm Android TV meetup
New improvements for web developers - frontend.fi, Helsinki
Mobile phone trends, user data & developer climate - frontend.fi, Helsinki

Recently uploaded (20)

PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
KodekX | Application Modernization Development
PPTX
Big Data Technologies - Introduction.pptx
PDF
GamePlan Trading System Review: Professional Trader's Honest Take
PDF
solutions_manual_-_materials___processing_in_manufacturing__demargo_.pdf
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Electronic commerce courselecture one. Pdf
PDF
Advanced Soft Computing BINUS July 2025.pdf
PDF
NewMind AI Monthly Chronicles - July 2025
PPTX
Cloud computing and distributed systems.
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PDF
cuic standard and advanced reporting.pdf
PDF
[발표본] 너의 과제는 클라우드에 있어_KTDS_김동현_20250524.pdf
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Empathic Computing: Creating Shared Understanding
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Modernizing your data center with Dell and AMD
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
KodekX | Application Modernization Development
Big Data Technologies - Introduction.pptx
GamePlan Trading System Review: Professional Trader's Honest Take
solutions_manual_-_materials___processing_in_manufacturing__demargo_.pdf
Unlocking AI with Model Context Protocol (MCP)
Electronic commerce courselecture one. Pdf
Advanced Soft Computing BINUS July 2025.pdf
NewMind AI Monthly Chronicles - July 2025
Cloud computing and distributed systems.
20250228 LYD VKU AI Blended-Learning.pptx
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
cuic standard and advanced reporting.pdf
[발표본] 너의 과제는 클라우드에 있어_KTDS_김동현_20250524.pdf
The Rise and Fall of 3GPP – Time for a Sabbatical?
Empathic Computing: Creating Shared Understanding
“AI and Expert System Decision Support & Business Intelligence Systems”
Modernizing your data center with Dell and AMD

JavaScript - Like a Box of Chocolates - jsDay

  • 1. JavaScript Like a Box of Chocolates
  • 12. “Are you telling me that I can’t get away anymore without getting deeply into Javascript?” - Developer
  • 13. “That is a disaster for me! I have made a career out of actively avoiding Javascript.” - Developer
  • 14. “If I cant continue to ignore Javascript, then you may as well amputate one of my limbs.” - Developer
  • 21. // Various "false" values var nullVal = null; var undefinedVal = undefined; var zeroVal = 0; var falseVal = false; var emptyString = ""; // All would equal false in an if-clause if (emptyString) { // Would never go in here }
  • 23. “Coercion is the practice of forcing another party to behave in an involuntary manner” - Wikipedia
  • 24. rci on c oe // Equality Ty pe if (7 == "7") { // true } // Identity if (7 === "7") { // false }
  • 25. // Type coercion var sum = "5" + 6 + 7; // 567
  • 26. // Prevent type coercion var sum = parseInt("5", 10) + 6 + 7; // 18
  • 28. // Self-invoking functions (function () { var investment = "Lieutenant Dan got me invested in some kind of fruit company."; })();
  • 30. // Using arguments function friends (friend1, friend2) { return friend1 + " & " + friend2; } // Lieutenant Dan & Bubba friends("Lieutenant Dan", "Bubba"); // Lieutenant Dan & undefined friends("Lieutenant Dan");
  • 31. // Using the arguments collection function friends () { var allFriends = []; for (var i=0, il=arguments.length; i<il; i++) { allFriends.push(arguments[i]); }; return allFriends.join(" & "); } // Lieutenant Dan & Bubba friends("Lieutenant Dan", "Bubba"); // Lieutenant Dan friends("Lieutenant Dan");
  • 33. // Object declaration function Forrest () { this.firstName = "Forrest"; this.lastName = "Gump"; } var forrest = new Forrest();
  • 34. // Object declaration, literal style var forrest = { firstName : "Forrest", lastName : "Gump" };
  • 35. // Iterating over properties for (var item in forrest) { console.log(item + ": " + forrest[item]); }
  • 36. // Object declaration var forrest = { firstName : "Forrest" }; // Safe check for property if ("firstName" in forrest) { console.log(forrest.firstName); }
  • 38. // Object declaration function ForrestAsChild { this.firstName = "Forrest"; }; // Method set via prototype ForrestAsChild.prototype.runsFast = function () { return true; };
  • 39. // Object declaration function ForrestAsGrownup { this.joinsArmy = true; }; // Prototype for new object ForrestAsGrownup.prototype = new ForrestAsChild; // Method set via prototype ForrestAsGrownup.prototype.ruinsBathrobe = function () { return "I think I ruined your roommate's bathrobe"; };
  • 40. // Create an instance var forrest = new ForrestAsGrownup(); // Returns "I think I ruined your roommate's bathrobe" forrest.ruinsBathrobe(); // Returns true - from ForrestAsChild forrest.runsFast(); // Fails forrest.codesJavaScript();
  • 43. // Extending core JavaScript objects if (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"];
  • 45. // Scope - global or local // Global var quote = "I had run for 3 years, 2 months, 14 days, and 16 hours." function () { // Local var pantherParty = "I'm sorry I had to fight in the middle of your Black Panther party."; // Global question = "And so, you just ran?"; }
  • 46. // Global function meetingJFK () { var JFKQuestion = "Congratulations, how do you feel?"; // Local function forrestReply () { return "I gotta pee."; } return forrestReply(); } meetingJFK(); // I gotta pee forrestReply(); // Error: not accessible
  • 47. // Controlling scope function whoAmI () { return this.nodeName; } whoAmI(); // undefined whoAmI.call(document, "Hello"); // #document whoAmI.apply(document.body, ["Hello", "Greetings?"]); // BODY
  • 50. // closures function happens (what) { return function (verb) { return what + " " + verb; } } var action = happens("Shit"); action("happens"); // Shit happens
  • 52. // closures function happens (what) { return function (verb) { return what + " " + verb; } } var action = happens("Shit"); // Breaking it down var action = function (verb) { return "Shit" + " " + verb; };
  • 53. 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); };
  • 54. 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); };
  • 56. // Yahoo! JavaScript Module Pattern var forrest = function () { var firstName = "Forrest"; return { getFirstName : function () { return firstName; } }; }(); // Returns "Forrest" forrest.getFirstName();
  • 57. // Yahoo! JavaScript Module Pattern var forrest = function () { var firstName = "Forrest", getFirstName = function () { return firstName; }; return { getFirstName : getFirstName }; }(); // Returns "Forrest" forrest.getFirstName();
  • 59. // Namespacing var Movie = {}; // Yahoo! JavaScript Module Pattern Movie.forrest = function () { var lastName = "Gump"; return { firstName : "Forrest", getFirstName : function () { return this.firstName; } }; }();
  • 60. // Yahoo! JavaScript Module Pattern Movie.forrest = function () { var lastName = "Gump"; return { firstName : "Forrest", getFirstName : function () { return this.firstName; } }; }(); // Yahoo! JavaScript Module Pattern Movie.lieutenantDan = function () { var lastName = "Taylor"; return { firstName : "Dan", getFullName : function () { return Movie.forrest.getFirstName.call(this) + " " + lastName; } }; }(); Movie.lieutenantDan.getFullName();
  • 62. // Minimize DOM access document.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";
  • 63. // Minimize DOM access var 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;
  • 64. // Looping, variables and array lookups function 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); } }
  • 65. // Looping, variables and array lookups function 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); } }
  • 66. // Variable declaration function richAndStupid () { var rich = "And cause I was a gazillionaire, I cut that grass for free.", stupid = "Stupid is as stupid does."; }
  • 68. if (!("a" in window)) { var a = 1; } alert(a); // undefined
  • 69. function value () { return 1; } var value; alert(typeof value); // function
  • 70. function value () { return 1; } var value = 3; alert(typeof value); // number
  • 71. // Semicolon insertion return return; // Semicolon insertion { // Considered an empty block javascript : "Fantastic!" }; // Semicolon insertion, dummy line
  • 72. type of NaN // "number"
  • 74. var number = 5, check = { number: 10, getNum: function () { var number = 20; setTimeout(function () { alert(this.number); }, 10); } }; check.getNum(); // 5
  • 78. Robert Nyman http://robertnyman.com/speaking/ Twitter: @robertnyman Pictures: Chocolate: http://10000likes.blogspot.com/2010_11_01_archive.html Seinfeld: http://www.cartoonstock.com/directory/f/false_identity.asp Robocop: http://www.meh.ro/2010/04/01/murphy-as-robocop/ Forcing: http://www.pollsb.com/polls/p2116218-forcing_guy_look_computer_screen Bruce 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.html Verona flag: http://upload.wikimedia.org/wikipedia/commons/thumb/d/dc/Flag_of_Verona.svg/568px- David Hasselhof: http://www.wimereuxwobblers.co.uk/?page_id=6 Flag_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.html Euro Coin: http://accidentaldong.blogspot.com/2009/10/euro-uh-oh.html Extensible (dachshund): http://dog-breeds.findthebest.com/compare/16-55/Beagle-vs-Dachshund Most 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/4760120 Astronaut: 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-2 Internet Explorer 3: http://www.guidebookgallery.org/screenshots/browser Crockford: http://gemsres.com/story/nov07/468365/Crockford_New_4681.jpg Gandalf: http://web.mit.edu/kayla/Public/Backgrounds/LOTR%20Gandalf%204.JPG Name: http://blog.usa.gov/roller/govgab/tags/names Now: http://www.chronicbabe.com/articles/801/ Space: http://gucken.deviantart.com/art/Sunrise-in-Space-56420137 Axe: http://bestgamewallpapers.com/a3-the-age-of-sovereign/axe Fail better: http://ozguralaz.posterous.com/ever-tried-ever-failed-no-matt Money: 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.html Happy: 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