SlideShare a Scribd company logo
JavaScript Patterns

      Part One
Patterns


 ● Design Patterns
    ○ Gang of Four
    ○ Templates for any language


 ● Coding Patterns
    ○ JavaScript-specific strategies
    ○ Our main focus in this series


 ● Antipatterns
    ○ Common despite being dangerous
    ○ Introduce more problems than they solve
Object-Oriented
 ● JavaScript IS an object-oriented language

 ● 5 primitive types - these are not objects:
     ○ number, string, boolean, null, undefined
     ○ three of the primitives have object wrappers
         ■ Number(), String(), Boolean()

 ● 3 global properties
     ○ Infinity, NaN, undefined

 ● 13 global methods
    ○ decodeURI, encodeURI, escape, unescape, isFinite, isNaN,
      parseFloat, parseInt, eval, String, Number, decodeURIComponent,
      encodeURIComponent
Object-Oriented


 ● Objects
    ○ collection of key:value pairs
        ■ associative array, dictionary, hash
    ○ mutability - objects can be modified
    ○ two types:
        ■ Native JavaScript - defined by ES standard
           ■ built-in
           ■ user-defined (var o = {};)
        ■ Host - defined by browser/host
           ■ browser
           ■ DOM
Object-Oriented


 ● Functions are objects - can have:
    ○ properties
    ○ methods (other functions)


 ● Ther are no classes!
    ○ GoF: "Prefer object composition over inheritance."


 ● Prototypes
    ○ provide an 'inheritance-like' capability
    ○ 'prototype' is an object, not a class
    ○ every function object has a prototype property
    ○ avoid adding to JS built-ins
    ○ utilize for custom constructors
ECMAScript 5


● Standard which JS is based on


● Version 5
   ○ new objects, methods and properties
   ○ 'strict mode'
       ■ removes features
       ■ makes programs simpler and less error prone
       ■ backward compatible
       ■ 'use strict' once per scope
   ○ not yet supported
   ○ keep an eye out for the transition
JSLint


● JavaScript
   ○ interpreted
   ○ no static compile-time checks = hard to debug


● Douglas Crockford
   ○ this tool "will hurt your feelings"
   ○ but also inspire confidence


● jslint.com
    ○ improve code quality
    ○ find syntax errors
    ○ find simple omissions
    ○ has a wide variety of settings: 'strict mode' compliance
The Console


● present in most browsers
   ○ Gecko: Firebug
   ○ Webkit: Web Inspector
   ○ Trident: Developer Tools


● less obtrusive than alert()


● console's output methods
   ○ console.log() outputs params
   ○ console.dir() enumerates
   ○ type in directly
Authoring Essentials


 ● Write Maintainable Code
    ○ readable
    ○ consistent
    ○ predictable
    ○ focused
    ○ documented


 ● Know Your Scope
    ○ local
    ○ global
Global


● declared outside of any function


● browsers provide access via 'window' property


● shared among all code, including any 3rd party libs


● use as few as possible, strategies include:
   ○ namespaces
   ○ immediate functions
   ○ 'var' declarations
Global
● 'var' declarations
    ○ var inside any function
        ■ "var foo = {}"
            ■ makes a foo object local to that function
        ■ "bar = {}"
            ■ adds a bar property to the global
        ■ "var nix = bix = 0"
            ■ makes a local nix and a global bix
    ○ var outside any function
        ■ makes a global variable (not a global property)


● 'var's CAN NOT be deleted, properties can


● ES5 strict mode throws error for undeclared variable assignments
Variable Hoisting


● all var declarations in a function act as if declared at top


● so just declare them at top to avoid confusion
                      var scope = "global";
                      function f(){
                          alert(scope);        //undefined
                          var scope = "local";
                          alert(scope);        //local
                      }
                      f();
                      ____________________________


                      var scope = "global";
                      function f(){
                          var scope;
                          alert(scope);       //undefined
                          scope = "local";
                          alert(scope);       //local
                      }
                      f();
Loops


● 'for' loop
    ○ cache the length value of your collection
         ■ Array
         ■ HTMLCollection
            ■ especially bad
            ■ live queries on the DOM
    ○ exception: when modifying length of collection


● try to avoid nested loops at all costs
    ○ look for other ways
    ○ ask around
    ○ might not be obvious, but worth it
Loops


● 'for in' loops
    ○ enumeration of objects
         ■ ...technically can be used with arrays
         ■ ...but not recommended
    ○ hasOwnProperty()
         ■ important defensive strategy
         ■ filters out prototype chain
         ■ ...but has performance implication
         ■ if your object has redefined hasOwnProperty()
              ■ Object.prototype.hasOwnProperty.call(obj, i)
Augmenting Built-ins


● it's done via 'prototype'
     ○ Object.prototype.newMethodForAll = function(){};


● but it's best not done at all
   ○ less predictable
   ○ other devs won't get it
   ○ it will show up in loops that don't defend against it


● exception conditions - all 3 must be met!
   1. if ES or JS will eventually implement anyway
   2. if you are sure it doesn't already exist
   3. you clearly document AND communicate to your team
   4. example: Array.isArray

More Related Content

PDF
Grant Rogerson SDEC2015
PDF
Swift for-rubyists
PDF
Ruxmon.2013-08.-.CodeBro!
PPTX
PDF
Kotlin workshop 2018-06-11
PPTX
JS knowing-nuances
KEY
The JavaScript Programming Primer
PPTX
Mono + .NET Core = ❤️
Grant Rogerson SDEC2015
Swift for-rubyists
Ruxmon.2013-08.-.CodeBro!
Kotlin workshop 2018-06-11
JS knowing-nuances
The JavaScript Programming Primer
Mono + .NET Core = ❤️

What's hot (7)

PPTX
Lesson 4
PDF
Python intro
PDF
Extending Node.js using C++
PPTX
Storage classes
PPTX
Coding convention
PDF
How to write Ruby extensions with Crystal
PDF
Golang and Eco-System Introduction / Overview
Lesson 4
Python intro
Extending Node.js using C++
Storage classes
Coding convention
How to write Ruby extensions with Crystal
Golang and Eco-System Introduction / Overview
Ad

Viewers also liked (19)

PDF
JavaScript: Patterns, Part 3
PDF
JavaScript: Patterns, Part 2
PPT
Presentation janice baay
PDF
Android security
PDF
Code Kata
PDF
iOS release engineering
PPT
Presentation janice baay
PDF
Clean Code
PPT
Presentation janice baay
PDF
JavaScript: The Good Parts
PDF
Code Kata: String Calculator in Flex
PDF
Classic Mistakes
PPT
Presentation janice baay
PDF
Function Points
PDF
OpenGL ES on Android
PDF
Software Development Fundamentals
PDF
iOS: A Broad Overview
PPTX
Javascript Common Design Patterns
PDF
iOS App Dev
JavaScript: Patterns, Part 3
JavaScript: Patterns, Part 2
Presentation janice baay
Android security
Code Kata
iOS release engineering
Presentation janice baay
Clean Code
Presentation janice baay
JavaScript: The Good Parts
Code Kata: String Calculator in Flex
Classic Mistakes
Presentation janice baay
Function Points
OpenGL ES on Android
Software Development Fundamentals
iOS: A Broad Overview
Javascript Common Design Patterns
iOS App Dev
Ad

Similar to JavaScript: Patterns, Part 1 (20)

KEY
Exciting JavaScript - Part I
PPTX
Advanced javascript from zero to hero in this PPT
PDF
Ruxmon feb 2013 what happened to rails
PDF
JavaScript Good Practices
PDF
ECMAScript 6 from an Attacker's Perspective - Breaking Frameworks, Sandboxes,...
PDF
24 uses for perl6
PDF
Twins: OOP and FP
PPTX
Diagnosing HotSpot JVM Memory Leaks with JFR and JMC
KEY
Exciting JavaScript - Part II
PDF
JavaScript From Hell - CONFidence 2.0 2009
KEY
Dojo for programmers (TXJS 2010)
PDF
How does Ansible's agentless architecture work?
PDF
Whirlwind tour of the Runtime Dynamic Linker
PDF
Blocks & GCD
PDF
Louis Loizides iOS Programming Introduction
PDF
iOS Programming Intro
PDF
Android Variants, Hacks, Tricks and Resources presented at AnDevConII
PPTX
Best practices for ansible
PDF
Smalltalk, the dynamic language
PDF
HTML, CSS & Javascript Architecture (extended version) - Jan Kraus
Exciting JavaScript - Part I
Advanced javascript from zero to hero in this PPT
Ruxmon feb 2013 what happened to rails
JavaScript Good Practices
ECMAScript 6 from an Attacker's Perspective - Breaking Frameworks, Sandboxes,...
24 uses for perl6
Twins: OOP and FP
Diagnosing HotSpot JVM Memory Leaks with JFR and JMC
Exciting JavaScript - Part II
JavaScript From Hell - CONFidence 2.0 2009
Dojo for programmers (TXJS 2010)
How does Ansible's agentless architecture work?
Whirlwind tour of the Runtime Dynamic Linker
Blocks & GCD
Louis Loizides iOS Programming Introduction
iOS Programming Intro
Android Variants, Hacks, Tricks and Resources presented at AnDevConII
Best practices for ansible
Smalltalk, the dynamic language
HTML, CSS & Javascript Architecture (extended version) - Jan Kraus

Recently uploaded (20)

PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
Advanced IT Governance
PDF
NewMind AI Monthly Chronicles - July 2025
PPTX
MYSQL Presentation for SQL database connectivity
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
madgavkar20181017ppt McKinsey Presentation.pdf
PPT
Teaching material agriculture food technology
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Electronic commerce courselecture one. Pdf
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
KodekX | Application Modernization Development
Mobile App Security Testing_ A Comprehensive Guide.pdf
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Advanced IT Governance
NewMind AI Monthly Chronicles - July 2025
MYSQL Presentation for SQL database connectivity
20250228 LYD VKU AI Blended-Learning.pptx
The AUB Centre for AI in Media Proposal.docx
Reach Out and Touch Someone: Haptics and Empathic Computing
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Network Security Unit 5.pdf for BCA BBA.
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
madgavkar20181017ppt McKinsey Presentation.pdf
Teaching material agriculture food technology
Review of recent advances in non-invasive hemoglobin estimation
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
NewMind AI Weekly Chronicles - August'25 Week I
Electronic commerce courselecture one. Pdf
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
KodekX | Application Modernization Development

JavaScript: Patterns, Part 1

  • 2. Patterns ● Design Patterns ○ Gang of Four ○ Templates for any language ● Coding Patterns ○ JavaScript-specific strategies ○ Our main focus in this series ● Antipatterns ○ Common despite being dangerous ○ Introduce more problems than they solve
  • 3. Object-Oriented ● JavaScript IS an object-oriented language ● 5 primitive types - these are not objects: ○ number, string, boolean, null, undefined ○ three of the primitives have object wrappers ■ Number(), String(), Boolean() ● 3 global properties ○ Infinity, NaN, undefined ● 13 global methods ○ decodeURI, encodeURI, escape, unescape, isFinite, isNaN, parseFloat, parseInt, eval, String, Number, decodeURIComponent, encodeURIComponent
  • 4. Object-Oriented ● Objects ○ collection of key:value pairs ■ associative array, dictionary, hash ○ mutability - objects can be modified ○ two types: ■ Native JavaScript - defined by ES standard ■ built-in ■ user-defined (var o = {};) ■ Host - defined by browser/host ■ browser ■ DOM
  • 5. Object-Oriented ● Functions are objects - can have: ○ properties ○ methods (other functions) ● Ther are no classes! ○ GoF: "Prefer object composition over inheritance." ● Prototypes ○ provide an 'inheritance-like' capability ○ 'prototype' is an object, not a class ○ every function object has a prototype property ○ avoid adding to JS built-ins ○ utilize for custom constructors
  • 6. ECMAScript 5 ● Standard which JS is based on ● Version 5 ○ new objects, methods and properties ○ 'strict mode' ■ removes features ■ makes programs simpler and less error prone ■ backward compatible ■ 'use strict' once per scope ○ not yet supported ○ keep an eye out for the transition
  • 7. JSLint ● JavaScript ○ interpreted ○ no static compile-time checks = hard to debug ● Douglas Crockford ○ this tool "will hurt your feelings" ○ but also inspire confidence ● jslint.com ○ improve code quality ○ find syntax errors ○ find simple omissions ○ has a wide variety of settings: 'strict mode' compliance
  • 8. The Console ● present in most browsers ○ Gecko: Firebug ○ Webkit: Web Inspector ○ Trident: Developer Tools ● less obtrusive than alert() ● console's output methods ○ console.log() outputs params ○ console.dir() enumerates ○ type in directly
  • 9. Authoring Essentials ● Write Maintainable Code ○ readable ○ consistent ○ predictable ○ focused ○ documented ● Know Your Scope ○ local ○ global
  • 10. Global ● declared outside of any function ● browsers provide access via 'window' property ● shared among all code, including any 3rd party libs ● use as few as possible, strategies include: ○ namespaces ○ immediate functions ○ 'var' declarations
  • 11. Global ● 'var' declarations ○ var inside any function ■ "var foo = {}" ■ makes a foo object local to that function ■ "bar = {}" ■ adds a bar property to the global ■ "var nix = bix = 0" ■ makes a local nix and a global bix ○ var outside any function ■ makes a global variable (not a global property) ● 'var's CAN NOT be deleted, properties can ● ES5 strict mode throws error for undeclared variable assignments
  • 12. Variable Hoisting ● all var declarations in a function act as if declared at top ● so just declare them at top to avoid confusion var scope = "global"; function f(){ alert(scope); //undefined var scope = "local"; alert(scope); //local } f(); ____________________________ var scope = "global"; function f(){ var scope; alert(scope); //undefined scope = "local"; alert(scope); //local } f();
  • 13. Loops ● 'for' loop ○ cache the length value of your collection ■ Array ■ HTMLCollection ■ especially bad ■ live queries on the DOM ○ exception: when modifying length of collection ● try to avoid nested loops at all costs ○ look for other ways ○ ask around ○ might not be obvious, but worth it
  • 14. Loops ● 'for in' loops ○ enumeration of objects ■ ...technically can be used with arrays ■ ...but not recommended ○ hasOwnProperty() ■ important defensive strategy ■ filters out prototype chain ■ ...but has performance implication ■ if your object has redefined hasOwnProperty() ■ Object.prototype.hasOwnProperty.call(obj, i)
  • 15. Augmenting Built-ins ● it's done via 'prototype' ○ Object.prototype.newMethodForAll = function(){}; ● but it's best not done at all ○ less predictable ○ other devs won't get it ○ it will show up in loops that don't defend against it ● exception conditions - all 3 must be met! 1. if ES or JS will eventually implement anyway 2. if you are sure it doesn't already exist 3. you clearly document AND communicate to your team 4. example: Array.isArray