SlideShare a Scribd company logo
1 of 80
Download to read offline
JavaScript
Like a Box of Chocolates
@robertnyman

http://robertnyman.com
ā€œ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
// 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
}
ā€œ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
// Self-invoking functions
(function () {
    var investment = "Lieutenant Dan got me
invested in some kind of fruit company.";
})();
// 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");
// 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);
}
// 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
// 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"];
// 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
// closures
function happens (what) {
    return function (verb) {
        return what + " " + verb;
    }
}

var action = happens("Shit");

action("happens"); // Shit happens
// 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);
};
// 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();
// 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();
// 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.";
}
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
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 ļ¬‚ag: http://scrapetv.com/News/News%20Pages/usa/Images/swedish-ļ¬‚ag.jpg                                   Overloading: http://theshadowhive.blogspot.com/2010/04/mutating-chaos-gene.html
Verona ļ¬‚ag: 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/ļ¬‚ag: http://www.olssonfoto.se/JAlbum/SGP%202008%20Ullevi/slides/Svenska%20ļ¬‚aggan.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.ļ¬ndthebest.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.ļ¬shingfury.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-proļ¬t-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

What's hot

Memory Leaks In Internet Explorer
Memory Leaks In Internet ExplorerMemory Leaks In Internet Explorer
Memory Leaks In Internet ExplorerChristopher Blum
Ā 
Memory Leaks In Internet Explorer
Memory Leaks In Internet ExplorerMemory Leaks In Internet Explorer
Memory Leaks In Internet ExplorerChristopher Blum
Ā 
Pragmatic JavaScript
Pragmatic JavaScriptPragmatic JavaScript
Pragmatic JavaScriptJohn Hann
Ā 
Java & Script ā”€ ęø…ē¾½
Java & Script ā”€ ęø…ē¾½Java & Script ā”€ ęø…ē¾½
Java & Script ā”€ ęø…ē¾½taobao.com
Ā 
Firefox OS learnings & visions, WebAPIs - budapest.mobile
Firefox OS learnings & visions, WebAPIs - budapest.mobileFirefox OS learnings & visions, WebAPIs - budapest.mobile
Firefox OS learnings & visions, WebAPIs - budapest.mobileRobert Nyman
Ā 
FizzBuzz恧ćÆć˜ć‚ć‚‹ćƒ†ć‚¹ćƒˆ
FizzBuzz恧ćÆć˜ć‚ć‚‹ćƒ†ć‚¹ćƒˆFizzBuzz恧ćÆć˜ć‚ć‚‹ćƒ†ć‚¹ćƒˆ
FizzBuzz恧ćÆć˜ć‚ć‚‹ćƒ†ć‚¹ćƒˆMasashi Shinbara
Ā 
å„²ć‹ć‚‹ćƒ‰ć‚­ćƒ„ćƒ”ćƒ³ćƒˆ
å„²ć‹ć‚‹ćƒ‰ć‚­ćƒ„ćƒ”ćƒ³ćƒˆå„²ć‹ć‚‹ćƒ‰ć‚­ćƒ„ćƒ”ćƒ³ćƒˆ
å„²ć‹ć‚‹ćƒ‰ć‚­ćƒ„ćƒ”ćƒ³ćƒˆYoshiki Shibukawa
Ā 
Dario Faggioli - Virtualization in the age of speculative execution HW bugs
Dario Faggioli - Virtualization in the age of speculative execution HW bugsDario Faggioli - Virtualization in the age of speculative execution HW bugs
Dario Faggioli - Virtualization in the age of speculative execution HW bugslinuxlab_conf
Ā 
Prototypal inheritance in JavaScript
Prototypal inheritance in JavaScriptPrototypal inheritance in JavaScript
Prototypal inheritance in JavaScriptMiroslav Obradović
Ā 
Beware sharp tools
Beware sharp toolsBeware sharp tools
Beware sharp toolsAgileOnTheBeach
Ā 
a hands on guide to django
a hands on guide to djangoa hands on guide to django
a hands on guide to djangoswee meng ng
Ā 
Using Buildout to Develop and Deploy Python Projects
Using Buildout to Develop and Deploy Python ProjectsUsing Buildout to Develop and Deploy Python Projects
Using Buildout to Develop and Deploy Python ProjectsClayton Parker
Ā 
Celluloid - Beyond Sidekiq
Celluloid - Beyond SidekiqCelluloid - Beyond Sidekiq
Celluloid - Beyond SidekiqMarcelo Pinheiro
Ā 
A Backbone.js Tutorial for the Impatient - Part 1
A Backbone.js Tutorial for the Impatient - Part 1A Backbone.js Tutorial for the Impatient - Part 1
A Backbone.js Tutorial for the Impatient - Part 1jsalonen Salonen
Ā 

What's hot (20)

has("builds")
has("builds")has("builds")
has("builds")
Ā 
dojo.things()
dojo.things()dojo.things()
dojo.things()
Ā 
Memory Leaks In Internet Explorer
Memory Leaks In Internet ExplorerMemory Leaks In Internet Explorer
Memory Leaks In Internet Explorer
Ā 
Memory Leaks In Internet Explorer
Memory Leaks In Internet ExplorerMemory Leaks In Internet Explorer
Memory Leaks In Internet Explorer
Ā 
Pragmatic JavaScript
Pragmatic JavaScriptPragmatic JavaScript
Pragmatic JavaScript
Ā 
Java & Script ā”€ ęø…ē¾½
Java & Script ā”€ ęø…ē¾½Java & Script ā”€ ęø…ē¾½
Java & Script ā”€ ęø…ē¾½
Ā 
Firefox OS learnings & visions, WebAPIs - budapest.mobile
Firefox OS learnings & visions, WebAPIs - budapest.mobileFirefox OS learnings & visions, WebAPIs - budapest.mobile
Firefox OS learnings & visions, WebAPIs - budapest.mobile
Ā 
Clean code
Clean codeClean code
Clean code
Ā 
FizzBuzz恧ćÆć˜ć‚ć‚‹ćƒ†ć‚¹ćƒˆ
FizzBuzz恧ćÆć˜ć‚ć‚‹ćƒ†ć‚¹ćƒˆFizzBuzz恧ćÆć˜ć‚ć‚‹ćƒ†ć‚¹ćƒˆ
FizzBuzz恧ćÆć˜ć‚ć‚‹ćƒ†ć‚¹ćƒˆ
Ā 
ąø ąø²ąø©ąø² C
ąø ąø²ąø©ąø² Cąø ąø²ąø©ąø² C
ąø ąø²ąø©ąø² C
Ā 
Ruby Robots
Ruby RobotsRuby Robots
Ruby Robots
Ā 
å„²ć‹ć‚‹ćƒ‰ć‚­ćƒ„ćƒ”ćƒ³ćƒˆ
å„²ć‹ć‚‹ćƒ‰ć‚­ćƒ„ćƒ”ćƒ³ćƒˆå„²ć‹ć‚‹ćƒ‰ć‚­ćƒ„ćƒ”ćƒ³ćƒˆ
å„²ć‹ć‚‹ćƒ‰ć‚­ćƒ„ćƒ”ćƒ³ćƒˆ
Ā 
Dario Faggioli - Virtualization in the age of speculative execution HW bugs
Dario Faggioli - Virtualization in the age of speculative execution HW bugsDario Faggioli - Virtualization in the age of speculative execution HW bugs
Dario Faggioli - Virtualization in the age of speculative execution HW bugs
Ā 
Prototypal inheritance in JavaScript
Prototypal inheritance in JavaScriptPrototypal inheritance in JavaScript
Prototypal inheritance in JavaScript
Ā 
Beware sharp tools
Beware sharp toolsBeware sharp tools
Beware sharp tools
Ā 
a hands on guide to django
a hands on guide to djangoa hands on guide to django
a hands on guide to django
Ā 
Using Buildout to Develop and Deploy Python Projects
Using Buildout to Develop and Deploy Python ProjectsUsing Buildout to Develop and Deploy Python Projects
Using Buildout to Develop and Deploy Python Projects
Ā 
Celluloid - Beyond Sidekiq
Celluloid - Beyond SidekiqCelluloid - Beyond Sidekiq
Celluloid - Beyond Sidekiq
Ā 
Mojolicious
MojoliciousMojolicious
Mojolicious
Ā 
A Backbone.js Tutorial for the Impatient - Part 1
A Backbone.js Tutorial for the Impatient - Part 1A Backbone.js Tutorial for the Impatient - Part 1
A Backbone.js Tutorial for the Impatient - Part 1
Ā 

Similar to JavaScript - Like a Box of Chocolates - jsDay

JavaScript & HTML5 - Brave New World
JavaScript & HTML5 - Brave New WorldJavaScript & HTML5 - Brave New World
JavaScript & HTML5 - Brave New WorldRobert Nyman
Ā 
JavaScript Survival Guide
JavaScript Survival GuideJavaScript Survival Guide
JavaScript Survival GuideGiordano Scalzo
Ā 
Intro to Advanced JavaScript
Intro to Advanced JavaScriptIntro to Advanced JavaScript
Intro to Advanced JavaScriptryanstout
Ā 
The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5arajivmordani
Ā 
HTML5 APIs - Where no man has gone before! - Altran
HTML5 APIs - Where no man has gone before! - AltranHTML5 APIs - Where no man has gone before! - Altran
HTML5 APIs - Where no man has gone before! - AltranRobert Nyman
Ā 
The Beauty of Java Script
The Beauty of Java ScriptThe Beauty of Java Script
The Beauty of Java ScriptMichael Girouard
Ā 
Web Optimization Summit: Coding for Performance
Web Optimization Summit: Coding for PerformanceWeb Optimization Summit: Coding for Performance
Web Optimization Summit: Coding for Performancejohndaviddalton
Ā 
JavaScript for PHP developers
JavaScript for PHP developersJavaScript for PHP developers
JavaScript for PHP developersStoyan Stefanov
Ā 
jQuery Data Manipulate API - A source code dissecting journey
jQuery Data Manipulate API - A source code dissecting journeyjQuery Data Manipulate API - A source code dissecting journey
jQuery Data Manipulate API - A source code dissecting journeyHuiyi Yan
Ā 
JavaScript Neednt Hurt - JavaBin talk
JavaScript Neednt Hurt - JavaBin talkJavaScript Neednt Hurt - JavaBin talk
JavaScript Neednt Hurt - JavaBin talkThomas Kjeldahl Nilsson
Ā 
jQuery: Events, Animation, Ajax
jQuery: Events, Animation, AjaxjQuery: Events, Animation, Ajax
jQuery: Events, Animation, AjaxConstantin Titarenko
Ā 
Bestpractices nl
Bestpractices nlBestpractices nl
Bestpractices nlWilfred Nas
Ā 
Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02Seri Moth
Ā 
Introduction to ECMAScript 2015
Introduction to ECMAScript 2015Introduction to ECMAScript 2015
Introduction to ECMAScript 2015Tomasz Dziuda
Ā 
Node.js for PHP developers
Node.js for PHP developersNode.js for PHP developers
Node.js for PHP developersAndrew Eddie
Ā 
Everyday's JS
Everyday's JSEveryday's JS
Everyday's JSAdib Mehedi
Ā 
jQuery: out with the old, in with the new
jQuery: out with the old, in with the newjQuery: out with the old, in with the new
jQuery: out with the old, in with the newRemy Sharp
Ā 
Plugin jQuery, Design Patterns
Plugin jQuery, Design PatternsPlugin jQuery, Design Patterns
Plugin jQuery, Design PatternsRobert Casanova
Ā 

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

JavaScript & HTML5 - Brave New World
JavaScript & HTML5 - Brave New WorldJavaScript & HTML5 - Brave New World
JavaScript & HTML5 - Brave New World
Ā 
JavaScript Survival Guide
JavaScript Survival GuideJavaScript Survival Guide
JavaScript Survival Guide
Ā 
Intro to Advanced JavaScript
Intro to Advanced JavaScriptIntro to Advanced JavaScript
Intro to Advanced JavaScript
Ā 
The Beauty Of Java Script V5a
The Beauty Of Java Script V5aThe Beauty Of Java Script V5a
The Beauty Of Java Script V5a
Ā 
HTML5 APIs - Where no man has gone before! - Altran
HTML5 APIs - Where no man has gone before! - AltranHTML5 APIs - Where no man has gone before! - Altran
HTML5 APIs - Where no man has gone before! - Altran
Ā 
The Beauty of Java Script
The Beauty of Java ScriptThe Beauty of Java Script
The Beauty of Java Script
Ā 
Web Optimization Summit: Coding for Performance
Web Optimization Summit: Coding for PerformanceWeb Optimization Summit: Coding for Performance
Web Optimization Summit: Coding for Performance
Ā 
Txjs
TxjsTxjs
Txjs
Ā 
JavaScript patterns
JavaScript patternsJavaScript patterns
JavaScript patterns
Ā 
JavaScript for PHP developers
JavaScript for PHP developersJavaScript for PHP developers
JavaScript for PHP developers
Ā 
jQuery Data Manipulate API - A source code dissecting journey
jQuery Data Manipulate API - A source code dissecting journeyjQuery Data Manipulate API - A source code dissecting journey
jQuery Data Manipulate API - A source code dissecting journey
Ā 
JavaScript Neednt Hurt - JavaBin talk
JavaScript Neednt Hurt - JavaBin talkJavaScript Neednt Hurt - JavaBin talk
JavaScript Neednt Hurt - JavaBin talk
Ā 
jQuery: Events, Animation, Ajax
jQuery: Events, Animation, AjaxjQuery: Events, Animation, Ajax
jQuery: Events, Animation, Ajax
Ā 
Bestpractices nl
Bestpractices nlBestpractices nl
Bestpractices nl
Ā 
Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02Jsphp 110312161301-phpapp02
Jsphp 110312161301-phpapp02
Ā 
Introduction to ECMAScript 2015
Introduction to ECMAScript 2015Introduction to ECMAScript 2015
Introduction to ECMAScript 2015
Ā 
Node.js for PHP developers
Node.js for PHP developersNode.js for PHP developers
Node.js for PHP developers
Ā 
Everyday's JS
Everyday's JSEveryday's JS
Everyday's JS
Ā 
jQuery: out with the old, in with the new
jQuery: out with the old, in with the newjQuery: out with the old, in with the new
jQuery: out with the old, in with the new
Ā 
Plugin jQuery, Design Patterns
Plugin jQuery, Design PatternsPlugin jQuery, Design Patterns
Plugin jQuery, Design Patterns
Ā 

More from Robert Nyman

Have you tried listening?
Have you tried listening?Have you tried listening?
Have you tried listening?Robert Nyman
Ā 
Building for Your Next Billion - Google I/O 2017
Building for Your Next Billion - Google I/O 2017Building for Your Next Billion - Google I/O 2017
Building for Your Next Billion - Google I/O 2017Robert Nyman
Ā 
Introduction to Google Daydream
Introduction to Google DaydreamIntroduction to Google Daydream
Introduction to Google DaydreamRobert Nyman
Ā 
Predictability for the Web
Predictability for the WebPredictability for the Web
Predictability for the WebRobert Nyman
Ā 
The Future of Progressive Web Apps - View Source conference, Berlin 2016
The Future of Progressive Web Apps - View Source conference, Berlin 2016The Future of Progressive Web Apps - View Source conference, Berlin 2016
The Future of Progressive Web Apps - View Source conference, Berlin 2016Robert Nyman
Ā 
The Future of the Web - Cold Front conference 2016
The Future of the Web - Cold Front conference 2016The Future of the Web - Cold Front conference 2016
The Future of the Web - Cold Front conference 2016Robert Nyman
Ā 
The Future of Progressive Web Apps - Google for Indonesia
The Future of Progressive Web Apps - Google for IndonesiaThe Future of Progressive Web Apps - Google for Indonesia
The Future of Progressive Web Apps - Google for IndonesiaRobert Nyman
Ā 
Google tech & products
Google tech & productsGoogle tech & products
Google tech & productsRobert Nyman
Ā 
Introduction to Progressive Web Apps, Google Developer Summit, Seoul - South ...
Introduction to Progressive Web Apps, Google Developer Summit, Seoul - South ...Introduction to Progressive Web Apps, Google Developer Summit, Seoul - South ...
Introduction to Progressive Web Apps, Google Developer Summit, Seoul - South ...Robert Nyman
Ā 
Progressive Web Apps keynote, Google Developer Summit, Tokyo, Japan
Progressive Web Apps keynote, Google Developer Summit, Tokyo, JapanProgressive Web Apps keynote, Google Developer Summit, Tokyo, Japan
Progressive Web Apps keynote, Google Developer Summit, Tokyo, JapanRobert Nyman
Ā 
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 - keynote at Riga D...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 - keynote at Riga D...Robert Nyman
Ā 
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 - Bulgaria Web Summ...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 - Bulgaria Web Summ...Robert Nyman
Ā 
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 - IstanbulThe 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 - IstanbulRobert Nyman
Ā 
The web - What it has, what it lacks and where it must go
The web - What it has, what it lacks and where it must goThe web - What it has, what it lacks and where it must go
The web - What it has, what it lacks and where it must goRobert Nyman
Ā 
Google, the future and possibilities
Google, the future and possibilitiesGoogle, the future and possibilities
Google, the future and possibilitiesRobert Nyman
Ā 
Developer Relations in the Nordics
Developer Relations in the NordicsDeveloper Relations in the Nordics
Developer Relations in the NordicsRobert Nyman
Ā 
What is Developer Relations?
What is Developer Relations?What is Developer Relations?
What is Developer Relations?Robert Nyman
Ā 
Android TV Introduction - Stockholm Android TV meetup
Android TV Introduction - Stockholm Android TV meetupAndroid TV Introduction - Stockholm Android TV meetup
Android TV Introduction - Stockholm Android TV meetupRobert Nyman
Ā 
New improvements for web developers - frontend.fi, Helsinki
New improvements for web developers - frontend.fi, HelsinkiNew improvements for web developers - frontend.fi, Helsinki
New improvements for web developers - frontend.fi, HelsinkiRobert Nyman
Ā 
Mobile phone trends, user data & developer climate - frontend.fi, Helsinki
Mobile phone trends, user data & developer climate - frontend.fi, HelsinkiMobile phone trends, user data & developer climate - frontend.fi, Helsinki
Mobile phone trends, user data & developer climate - frontend.fi, HelsinkiRobert Nyman
Ā 

More from Robert Nyman (20)

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

Recently uploaded

Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
Ā 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
Ā 
šŸ¬ The future of MySQL is Postgres šŸ˜
šŸ¬  The future of MySQL is Postgres   šŸ˜šŸ¬  The future of MySQL is Postgres   šŸ˜
šŸ¬ The future of MySQL is Postgres šŸ˜RTylerCroy
Ā 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
Ā 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
Ā 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Principled Technologies
Ā 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
Ā 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
Ā 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
Ā 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
Ā 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
Ā 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
Ā 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
Ā 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
Ā 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
Ā 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
Ā 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
Ā 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024SynarionITSolutions
Ā 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
Ā 

Recently uploaded (20)

Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
Ā 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Ā 
šŸ¬ The future of MySQL is Postgres šŸ˜
šŸ¬  The future of MySQL is Postgres   šŸ˜šŸ¬  The future of MySQL is Postgres   šŸ˜
šŸ¬ The future of MySQL is Postgres šŸ˜
Ā 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
Ā 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
Ā 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Ā 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
Ā 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Ā 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Ā 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
Ā 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
Ā 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Ā 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
Ā 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Ā 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
Ā 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
Ā 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Ā 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
Ā 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
Ā 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Ā 

JavaScript - Like a Box of Chocolates - jsDay

  • 1. JavaScript Like a Box of Chocolates
  • 2.
  • 3.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 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
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 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 }
  • 22.
  • 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
  • 27.
  • 28. // Self-invoking functions (function () { var investment = "Lieutenant Dan got me invested in some kind of fruit company."; })();
  • 29.
  • 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");
  • 32.
  • 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); }
  • 37.
  • 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();
  • 42.
  • 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"];
  • 44.
  • 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
  • 48.
  • 49.
  • 50. // closures function happens (what) { return function (verb) { return what + " " + verb; } } var action = happens("Shit"); action("happens"); // Shit happens
  • 51.
  • 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); };
  • 55.
  • 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();
  • 58.
  • 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();
  • 61.
  • 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."; }
  • 67.
  • 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
  • 76.
  • 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 ļ¬‚ag: http://scrapetv.com/News/News%20Pages/usa/Images/swedish-ļ¬‚ag.jpg Overloading: http://theshadowhive.blogspot.com/2010/04/mutating-chaos-gene.html Verona ļ¬‚ag: 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/ļ¬‚ag: http://www.olssonfoto.se/JAlbum/SGP%202008%20Ullevi/slides/Svenska%20ļ¬‚aggan.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.ļ¬ndthebest.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.ļ¬shingfury.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-proļ¬t-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