SlideShare una empresa de Scribd logo
1 de 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

Más contenido relacionado

La actualidad más candente

La actualidad más candente (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
 

Destacado

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
 

Destacado (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 a 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 a 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
 

Último

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
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
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
 
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
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
🐬 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
 

Último (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
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
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
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 

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