SlideShare a Scribd company logo
1 of 15
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

What's hot

What's hot (7)

Lesson 4
Lesson 4Lesson 4
Lesson 4
 
Python intro
Python introPython intro
Python intro
 
Extending Node.js using C++
Extending Node.js using C++Extending Node.js using C++
Extending Node.js using C++
 
Storage classes
Storage classesStorage classes
Storage classes
 
Coding convention
Coding conventionCoding convention
Coding convention
 
How to write Ruby extensions with Crystal
How to write Ruby extensions with CrystalHow to write Ruby extensions with Crystal
How to write Ruby extensions with Crystal
 
Golang and Eco-System Introduction / Overview
Golang and Eco-System Introduction / OverviewGolang and Eco-System Introduction / Overview
Golang and Eco-System Introduction / Overview
 

Viewers also liked

JavaScript: Patterns, Part 3
JavaScript: Patterns, Part  3JavaScript: Patterns, Part  3
JavaScript: Patterns, Part 3Chris Farrell
 
JavaScript: Patterns, Part 2
JavaScript: Patterns, Part  2JavaScript: Patterns, Part  2
JavaScript: Patterns, Part 2Chris Farrell
 
Presentation janice baay
Presentation janice baayPresentation janice baay
Presentation janice baayJanice Baay
 
iOS release engineering
iOS release engineeringiOS release engineering
iOS release engineeringChris Farrell
 
Presentation janice baay
Presentation janice baayPresentation janice baay
Presentation janice baayJanice Baay
 
Presentation janice baay
Presentation janice baayPresentation janice baay
Presentation janice baayJanice Baay
 
JavaScript: The Good Parts
JavaScript: The Good PartsJavaScript: The Good Parts
JavaScript: The Good PartsChris Farrell
 
Code Kata: String Calculator in Flex
Code Kata: String Calculator in FlexCode Kata: String Calculator in Flex
Code Kata: String Calculator in FlexChris Farrell
 
Presentation janice baay
Presentation janice baayPresentation janice baay
Presentation janice baayJanice Baay
 
OpenGL ES on Android
OpenGL ES on AndroidOpenGL ES on Android
OpenGL ES on AndroidChris Farrell
 
Software Development Fundamentals
Software Development FundamentalsSoftware Development Fundamentals
Software Development FundamentalsChris Farrell
 
iOS: A Broad Overview
iOS: A Broad OverviewiOS: A Broad Overview
iOS: A Broad OverviewChris Farrell
 
Javascript Common Design Patterns
Javascript Common Design PatternsJavascript Common Design Patterns
Javascript Common Design PatternsPham Huy Tung
 

Viewers also liked (19)

JavaScript: Patterns, Part 3
JavaScript: Patterns, Part  3JavaScript: Patterns, Part  3
JavaScript: Patterns, Part 3
 
JavaScript: Patterns, Part 2
JavaScript: Patterns, Part  2JavaScript: Patterns, Part  2
JavaScript: Patterns, Part 2
 
Presentation janice baay
Presentation janice baayPresentation janice baay
Presentation janice baay
 
Android security
Android securityAndroid security
Android security
 
Code Kata
Code KataCode Kata
Code Kata
 
iOS release engineering
iOS release engineeringiOS release engineering
iOS release engineering
 
Presentation janice baay
Presentation janice baayPresentation janice baay
Presentation janice baay
 
Clean Code
Clean CodeClean Code
Clean Code
 
Presentation janice baay
Presentation janice baayPresentation janice baay
Presentation janice baay
 
JavaScript: The Good Parts
JavaScript: The Good PartsJavaScript: The Good Parts
JavaScript: The Good Parts
 
Code Kata: String Calculator in Flex
Code Kata: String Calculator in FlexCode Kata: String Calculator in Flex
Code Kata: String Calculator in Flex
 
Classic Mistakes
Classic MistakesClassic Mistakes
Classic Mistakes
 
Presentation janice baay
Presentation janice baayPresentation janice baay
Presentation janice baay
 
Function Points
Function PointsFunction Points
Function Points
 
OpenGL ES on Android
OpenGL ES on AndroidOpenGL ES on Android
OpenGL ES on Android
 
Software Development Fundamentals
Software Development FundamentalsSoftware Development Fundamentals
Software Development Fundamentals
 
iOS: A Broad Overview
iOS: A Broad OverviewiOS: A Broad Overview
iOS: A Broad Overview
 
Javascript Common Design Patterns
Javascript Common Design PatternsJavascript Common Design Patterns
Javascript Common Design Patterns
 
iOS App Dev
iOS App Dev iOS App Dev
iOS App Dev
 

Similar to JavaScript: Patterns, Part 1

Exciting JavaScript - Part I
Exciting JavaScript - Part IExciting JavaScript - Part I
Exciting JavaScript - Part IEugene Lazutkin
 
Ruxmon feb 2013 what happened to rails
Ruxmon feb 2013   what happened to railsRuxmon feb 2013   what happened to rails
Ruxmon feb 2013 what happened to railssnyff
 
ECMAScript 6 from an Attacker's Perspective - Breaking Frameworks, Sandboxes,...
ECMAScript 6 from an Attacker's Perspective - Breaking Frameworks, Sandboxes,...ECMAScript 6 from an Attacker's Perspective - Breaking Frameworks, Sandboxes,...
ECMAScript 6 from an Attacker's Perspective - Breaking Frameworks, Sandboxes,...Mario Heiderich
 
Diagnosing HotSpot JVM Memory Leaks with JFR and JMC
Diagnosing HotSpot JVM Memory Leaks with JFR and JMCDiagnosing HotSpot JVM Memory Leaks with JFR and JMC
Diagnosing HotSpot JVM Memory Leaks with JFR and JMCMushfekur Rahman
 
Exciting JavaScript - Part II
Exciting JavaScript - Part IIExciting JavaScript - Part II
Exciting JavaScript - Part IIEugene Lazutkin
 
JavaScript From Hell - CONFidence 2.0 2009
JavaScript From Hell - CONFidence 2.0 2009JavaScript From Hell - CONFidence 2.0 2009
JavaScript From Hell - CONFidence 2.0 2009Mario Heiderich
 
Dojo for programmers (TXJS 2010)
Dojo for programmers (TXJS 2010)Dojo for programmers (TXJS 2010)
Dojo for programmers (TXJS 2010)Eugene Lazutkin
 
How does Ansible's agentless architecture work?
How does Ansible's agentless architecture work?How does Ansible's agentless architecture work?
How does Ansible's agentless architecture work?jtyr
 
Whirlwind tour of the Runtime Dynamic Linker
Whirlwind tour of the Runtime Dynamic LinkerWhirlwind tour of the Runtime Dynamic Linker
Whirlwind tour of the Runtime Dynamic LinkerGonçalo Gomes
 
Blocks & GCD
Blocks & GCDBlocks & GCD
Blocks & GCDrsebbe
 
AOT-compilation of JavaScript with V8
AOT-compilation of JavaScript with V8AOT-compilation of JavaScript with V8
AOT-compilation of JavaScript with V8Phil Eaton
 
Louis Loizides iOS Programming Introduction
Louis Loizides iOS Programming IntroductionLouis Loizides iOS Programming Introduction
Louis Loizides iOS Programming IntroductionLou Loizides
 
iOS Programming Intro
iOS Programming IntroiOS Programming Intro
iOS Programming IntroLou Loizides
 
Android Variants, Hacks, Tricks and Resources presented at AnDevConII
Android Variants, Hacks, Tricks and Resources presented at AnDevConIIAndroid Variants, Hacks, Tricks and Resources presented at AnDevConII
Android Variants, Hacks, Tricks and Resources presented at AnDevConIIOpersys inc.
 
Best practices for ansible
Best practices for ansibleBest practices for ansible
Best practices for ansibleGeorge Shuklin
 
Smalltalk, the dynamic language
Smalltalk, the dynamic languageSmalltalk, the dynamic language
Smalltalk, the dynamic languagemohamedsamyali
 
HTML, CSS & Javascript Architecture (extended version) - Jan Kraus
HTML, CSS & Javascript Architecture (extended version) - Jan KrausHTML, CSS & Javascript Architecture (extended version) - Jan Kraus
HTML, CSS & Javascript Architecture (extended version) - Jan KrausWomen in Technology Poland
 

Similar to JavaScript: Patterns, Part 1 (20)

Exciting JavaScript - Part I
Exciting JavaScript - Part IExciting JavaScript - Part I
Exciting JavaScript - Part I
 
Ruxmon feb 2013 what happened to rails
Ruxmon feb 2013   what happened to railsRuxmon feb 2013   what happened to rails
Ruxmon feb 2013 what happened to rails
 
JavaScript Good Practices
JavaScript Good PracticesJavaScript Good Practices
JavaScript Good Practices
 
ECMAScript 6 from an Attacker's Perspective - Breaking Frameworks, Sandboxes,...
ECMAScript 6 from an Attacker's Perspective - Breaking Frameworks, Sandboxes,...ECMAScript 6 from an Attacker's Perspective - Breaking Frameworks, Sandboxes,...
ECMAScript 6 from an Attacker's Perspective - Breaking Frameworks, Sandboxes,...
 
24 uses for perl6
24 uses for perl624 uses for perl6
24 uses for perl6
 
Twins: OOP and FP
Twins: OOP and FPTwins: OOP and FP
Twins: OOP and FP
 
Diagnosing HotSpot JVM Memory Leaks with JFR and JMC
Diagnosing HotSpot JVM Memory Leaks with JFR and JMCDiagnosing HotSpot JVM Memory Leaks with JFR and JMC
Diagnosing HotSpot JVM Memory Leaks with JFR and JMC
 
Exciting JavaScript - Part II
Exciting JavaScript - Part IIExciting JavaScript - Part II
Exciting JavaScript - Part II
 
JavaScript From Hell - CONFidence 2.0 2009
JavaScript From Hell - CONFidence 2.0 2009JavaScript From Hell - CONFidence 2.0 2009
JavaScript From Hell - CONFidence 2.0 2009
 
Dojo for programmers (TXJS 2010)
Dojo for programmers (TXJS 2010)Dojo for programmers (TXJS 2010)
Dojo for programmers (TXJS 2010)
 
How does Ansible's agentless architecture work?
How does Ansible's agentless architecture work?How does Ansible's agentless architecture work?
How does Ansible's agentless architecture work?
 
Whirlwind tour of the Runtime Dynamic Linker
Whirlwind tour of the Runtime Dynamic LinkerWhirlwind tour of the Runtime Dynamic Linker
Whirlwind tour of the Runtime Dynamic Linker
 
Blocks & GCD
Blocks & GCDBlocks & GCD
Blocks & GCD
 
AOT-compilation of JavaScript with V8
AOT-compilation of JavaScript with V8AOT-compilation of JavaScript with V8
AOT-compilation of JavaScript with V8
 
Louis Loizides iOS Programming Introduction
Louis Loizides iOS Programming IntroductionLouis Loizides iOS Programming Introduction
Louis Loizides iOS Programming Introduction
 
iOS Programming Intro
iOS Programming IntroiOS Programming Intro
iOS Programming Intro
 
Android Variants, Hacks, Tricks and Resources presented at AnDevConII
Android Variants, Hacks, Tricks and Resources presented at AnDevConIIAndroid Variants, Hacks, Tricks and Resources presented at AnDevConII
Android Variants, Hacks, Tricks and Resources presented at AnDevConII
 
Best practices for ansible
Best practices for ansibleBest practices for ansible
Best practices for ansible
 
Smalltalk, the dynamic language
Smalltalk, the dynamic languageSmalltalk, the dynamic language
Smalltalk, the dynamic language
 
HTML, CSS & Javascript Architecture (extended version) - Jan Kraus
HTML, CSS & Javascript Architecture (extended version) - Jan KrausHTML, CSS & Javascript Architecture (extended version) - Jan Kraus
HTML, CSS & Javascript Architecture (extended version) - Jan Kraus
 

Recently uploaded

TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...TrustArc
 
The Ultimate Prompt Engineering Guide for Generative AI: Get the Most Out of ...
The Ultimate Prompt Engineering Guide for Generative AI: Get the Most Out of ...The Ultimate Prompt Engineering Guide for Generative AI: Get the Most Out of ...
The Ultimate Prompt Engineering Guide for Generative AI: Get the Most Out of ...SOFTTECHHUB
 
Design and Development of a Provenance Capture Platform for Data Science
Design and Development of a Provenance Capture Platform for Data ScienceDesign and Development of a Provenance Capture Platform for Data Science
Design and Development of a Provenance Capture Platform for Data SciencePaolo Missier
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontologyjohnbeverley2021
 
ChatGPT and Beyond - Elevating DevOps Productivity
ChatGPT and Beyond - Elevating DevOps ProductivityChatGPT and Beyond - Elevating DevOps Productivity
ChatGPT and Beyond - Elevating DevOps ProductivityVictorSzoltysek
 
Portal Kombat : extension du réseau de propagande russe
Portal Kombat : extension du réseau de propagande russePortal Kombat : extension du réseau de propagande russe
Portal Kombat : extension du réseau de propagande russe中 央社
 
AI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by AnitarajAI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by AnitarajAnitaRaj43
 
2024 May Patch Tuesday
2024 May Patch Tuesday2024 May Patch Tuesday
2024 May Patch TuesdayIvanti
 
JohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptxJohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptxJohnPollard37
 
Design Guidelines for Passkeys 2024.pptx
Design Guidelines for Passkeys 2024.pptxDesign Guidelines for Passkeys 2024.pptx
Design Guidelines for Passkeys 2024.pptxFIDO Alliance
 
Event-Driven Architecture Masterclass: Challenges in Stream Processing
Event-Driven Architecture Masterclass: Challenges in Stream ProcessingEvent-Driven Architecture Masterclass: Challenges in Stream Processing
Event-Driven Architecture Masterclass: Challenges in Stream ProcessingScyllaDB
 
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...panagenda
 
Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)
Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)
Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)Paige Cruz
 
Stronger Together: Developing an Organizational Strategy for Accessible Desig...
Stronger Together: Developing an Organizational Strategy for Accessible Desig...Stronger Together: Developing an Organizational Strategy for Accessible Desig...
Stronger Together: Developing an Organizational Strategy for Accessible Desig...caitlingebhard1
 
Microsoft CSP Briefing Pre-Engagement - Questionnaire
Microsoft CSP Briefing Pre-Engagement - QuestionnaireMicrosoft CSP Briefing Pre-Engagement - Questionnaire
Microsoft CSP Briefing Pre-Engagement - QuestionnaireExakis Nelite
 
Introduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMIntroduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMKumar Satyam
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
How to Check CNIC Information Online with Pakdata cf
How to Check CNIC Information Online with Pakdata cfHow to Check CNIC Information Online with Pakdata cf
How to Check CNIC Information Online with Pakdata cfdanishmna97
 
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptxHarnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptxFIDO Alliance
 
ERP Contender Series: Acumatica vs. Sage Intacct
ERP Contender Series: Acumatica vs. Sage IntacctERP Contender Series: Acumatica vs. Sage Intacct
ERP Contender Series: Acumatica vs. Sage IntacctBrainSell Technologies
 

Recently uploaded (20)

TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
 
The Ultimate Prompt Engineering Guide for Generative AI: Get the Most Out of ...
The Ultimate Prompt Engineering Guide for Generative AI: Get the Most Out of ...The Ultimate Prompt Engineering Guide for Generative AI: Get the Most Out of ...
The Ultimate Prompt Engineering Guide for Generative AI: Get the Most Out of ...
 
Design and Development of a Provenance Capture Platform for Data Science
Design and Development of a Provenance Capture Platform for Data ScienceDesign and Development of a Provenance Capture Platform for Data Science
Design and Development of a Provenance Capture Platform for Data Science
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
ChatGPT and Beyond - Elevating DevOps Productivity
ChatGPT and Beyond - Elevating DevOps ProductivityChatGPT and Beyond - Elevating DevOps Productivity
ChatGPT and Beyond - Elevating DevOps Productivity
 
Portal Kombat : extension du réseau de propagande russe
Portal Kombat : extension du réseau de propagande russePortal Kombat : extension du réseau de propagande russe
Portal Kombat : extension du réseau de propagande russe
 
AI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by AnitarajAI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by Anitaraj
 
2024 May Patch Tuesday
2024 May Patch Tuesday2024 May Patch Tuesday
2024 May Patch Tuesday
 
JohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptxJohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptx
 
Design Guidelines for Passkeys 2024.pptx
Design Guidelines for Passkeys 2024.pptxDesign Guidelines for Passkeys 2024.pptx
Design Guidelines for Passkeys 2024.pptx
 
Event-Driven Architecture Masterclass: Challenges in Stream Processing
Event-Driven Architecture Masterclass: Challenges in Stream ProcessingEvent-Driven Architecture Masterclass: Challenges in Stream Processing
Event-Driven Architecture Masterclass: Challenges in Stream Processing
 
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
 
Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)
Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)
Observability Concepts EVERY Developer Should Know (DevOpsDays Seattle)
 
Stronger Together: Developing an Organizational Strategy for Accessible Desig...
Stronger Together: Developing an Organizational Strategy for Accessible Desig...Stronger Together: Developing an Organizational Strategy for Accessible Desig...
Stronger Together: Developing an Organizational Strategy for Accessible Desig...
 
Microsoft CSP Briefing Pre-Engagement - Questionnaire
Microsoft CSP Briefing Pre-Engagement - QuestionnaireMicrosoft CSP Briefing Pre-Engagement - Questionnaire
Microsoft CSP Briefing Pre-Engagement - Questionnaire
 
Introduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMIntroduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDM
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
How to Check CNIC Information Online with Pakdata cf
How to Check CNIC Information Online with Pakdata cfHow to Check CNIC Information Online with Pakdata cf
How to Check CNIC Information Online with Pakdata cf
 
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptxHarnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
 
ERP Contender Series: Acumatica vs. Sage Intacct
ERP Contender Series: Acumatica vs. Sage IntacctERP Contender Series: Acumatica vs. Sage Intacct
ERP Contender Series: Acumatica vs. Sage Intacct
 

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