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

What's hot (7)

Lesson 4
Lesson 4Lesson 4
Lesson 4
Alex Honcharuk
 
Python intro
Python introPython intro
Python intro
Abhinav Upadhyay
 
Extending Node.js using C++
Extending Node.js using C++Extending Node.js using C++
Extending Node.js using C++
Kenneth Geisshirt
 
Storage classes
Storage classesStorage classes
Storage classes
priyanka jain
 
Coding convention
Coding conventionCoding convention
Coding convention
Khoa Nguyen
 
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
Anna (gaar4ica) Shcherbinina
 
Golang and Eco-System Introduction / Overview
Golang and Eco-System Introduction / OverviewGolang and Eco-System Introduction / Overview
Golang and Eco-System Introduction / Overview
Markus Schneider
 

Viewers also liked (19)

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

Similar to JavaScript: Patterns, Part 1 (20)

Awesomeness of JavaScript…almost
Awesomeness of JavaScript…almostAwesomeness of JavaScript…almost
Awesomeness of JavaScript…almost
Quinton Sheppard
 
JavaScript Primer
JavaScript PrimerJavaScript Primer
JavaScript Primer
Daniel Cousineau
 
JavaScript (without DOM)
JavaScript (without DOM)JavaScript (without DOM)
JavaScript (without DOM)
Piyush Katariya
 
Wakanday JS201 Best Practices
Wakanday JS201 Best PracticesWakanday JS201 Best Practices
Wakanday JS201 Best Practices
Juergen Fesslmeier
 
JavaScript: The Language
JavaScript: The LanguageJavaScript: The Language
JavaScript: The Language
Engage Software
 
LISA QooxdooTutorial Slides
LISA QooxdooTutorial SlidesLISA QooxdooTutorial Slides
LISA QooxdooTutorial Slides
Tobias Oetiker
 
JavaScript Neednt Hurt - JavaBin talk
JavaScript Neednt Hurt - JavaBin talkJavaScript Neednt Hurt - JavaBin talk
JavaScript Neednt Hurt - JavaBin talk
Thomas Kjeldahl Nilsson
 
Exciting JavaScript - Part I
Exciting JavaScript - Part IExciting JavaScript - Part I
Exciting JavaScript - Part I
Eugene Lazutkin
 
JavaScript Misunderstood
JavaScript MisunderstoodJavaScript Misunderstood
JavaScript Misunderstood
Bhavya Siddappa
 
ES6 - Next Generation Javascript
ES6 - Next Generation JavascriptES6 - Next Generation Javascript
ES6 - Next Generation Javascript
RameshNair6
 
JavaScript Basics
JavaScript BasicsJavaScript Basics
JavaScript Basics
Mats Bryntse
 
JavaScript Good Practices
JavaScript Good PracticesJavaScript Good Practices
JavaScript Good Practices
Jussi Pohjolainen
 
The JavaScript Programming Language
The JavaScript Programming LanguageThe JavaScript Programming Language
The JavaScript Programming Language
Mohammed Irfan Shaikh
 
Javascript The Good Parts v2
Javascript The Good Parts v2Javascript The Good Parts v2
Javascript The Good Parts v2
Federico Galassi
 
Lecture 03 - JQuery.pdf
Lecture 03 - JQuery.pdfLecture 03 - JQuery.pdf
Lecture 03 - JQuery.pdf
Lê Thưởng
 
Let's JavaScript
Let's JavaScriptLet's JavaScript
Let's JavaScript
Paweł Dorofiejczyk
 
Stop Programming in JavaScript By Luck
Stop Programming in JavaScript By LuckStop Programming in JavaScript By Luck
Stop Programming in JavaScript By Luck
sergioafp
 
Java Script Patterns
Java Script PatternsJava Script Patterns
Java Script Patterns
Allan Huang
 
Javascript fundamentals and not
Javascript fundamentals and notJavascript fundamentals and not
Javascript fundamentals and not
Salvatore Fazio
 
Intermediate JavaScript
Intermediate JavaScriptIntermediate JavaScript
Intermediate JavaScript
☆ Milan Adamovsky ☆
 
Awesomeness of JavaScript…almost
Awesomeness of JavaScript…almostAwesomeness of JavaScript…almost
Awesomeness of JavaScript…almost
Quinton Sheppard
 
JavaScript (without DOM)
JavaScript (without DOM)JavaScript (without DOM)
JavaScript (without DOM)
Piyush Katariya
 
JavaScript: The Language
JavaScript: The LanguageJavaScript: The Language
JavaScript: The Language
Engage Software
 
LISA QooxdooTutorial Slides
LISA QooxdooTutorial SlidesLISA QooxdooTutorial Slides
LISA QooxdooTutorial Slides
Tobias Oetiker
 
Exciting JavaScript - Part I
Exciting JavaScript - Part IExciting JavaScript - Part I
Exciting JavaScript - Part I
Eugene Lazutkin
 
JavaScript Misunderstood
JavaScript MisunderstoodJavaScript Misunderstood
JavaScript Misunderstood
Bhavya Siddappa
 
ES6 - Next Generation Javascript
ES6 - Next Generation JavascriptES6 - Next Generation Javascript
ES6 - Next Generation Javascript
RameshNair6
 
Javascript The Good Parts v2
Javascript The Good Parts v2Javascript The Good Parts v2
Javascript The Good Parts v2
Federico Galassi
 
Lecture 03 - JQuery.pdf
Lecture 03 - JQuery.pdfLecture 03 - JQuery.pdf
Lecture 03 - JQuery.pdf
Lê Thưởng
 
Stop Programming in JavaScript By Luck
Stop Programming in JavaScript By LuckStop Programming in JavaScript By Luck
Stop Programming in JavaScript By Luck
sergioafp
 
Java Script Patterns
Java Script PatternsJava Script Patterns
Java Script Patterns
Allan Huang
 
Javascript fundamentals and not
Javascript fundamentals and notJavascript fundamentals and not
Javascript fundamentals and not
Salvatore Fazio
 
Ad

Recently uploaded (20)

Mark Zuckerberg teams up with frenemy Palmer Luckey to shape the future of XR...
Mark Zuckerberg teams up with frenemy Palmer Luckey to shape the future of XR...Mark Zuckerberg teams up with frenemy Palmer Luckey to shape the future of XR...
Mark Zuckerberg teams up with frenemy Palmer Luckey to shape the future of XR...
Scott M. Graffius
 
How to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptxHow to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptx
Version 1 Analytics
 
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdfHow Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
Rejig Digital
 
Domino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use CasesDomino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use Cases
panagenda
 
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
angelo60207
 
Extend-Microsoft365-with-Copilot-agents.pptx
Extend-Microsoft365-with-Copilot-agents.pptxExtend-Microsoft365-with-Copilot-agents.pptx
Extend-Microsoft365-with-Copilot-agents.pptx
hoang971
 
Improving Developer Productivity With DORA, SPACE, and DevEx
Improving Developer Productivity With DORA, SPACE, and DevExImproving Developer Productivity With DORA, SPACE, and DevEx
Improving Developer Productivity With DORA, SPACE, and DevEx
Justin Reock
 
ISOIEC 42005 Revolutionalises AI Impact Assessment.pptx
ISOIEC 42005 Revolutionalises AI Impact Assessment.pptxISOIEC 42005 Revolutionalises AI Impact Assessment.pptx
ISOIEC 42005 Revolutionalises AI Impact Assessment.pptx
AyilurRamnath1
 
IntroSlides-May-BuildWithAi-EarthEngine.pdf
IntroSlides-May-BuildWithAi-EarthEngine.pdfIntroSlides-May-BuildWithAi-EarthEngine.pdf
IntroSlides-May-BuildWithAi-EarthEngine.pdf
Luiz Carneiro
 
The case for on-premises AI
The case for on-premises AIThe case for on-premises AI
The case for on-premises AI
Principled Technologies
 
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Safe Software
 
Data Virtualization: Bringing the Power of FME to Any Application
Data Virtualization: Bringing the Power of FME to Any ApplicationData Virtualization: Bringing the Power of FME to Any Application
Data Virtualization: Bringing the Power of FME to Any Application
Safe Software
 
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdfBoosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Alkin Tezuysal
 
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
Edge AI and Vision Alliance
 
LSNIF: Locally-Subdivided Neural Intersection Function
LSNIF: Locally-Subdivided Neural Intersection FunctionLSNIF: Locally-Subdivided Neural Intersection Function
LSNIF: Locally-Subdivided Neural Intersection Function
Takahiro Harada
 
Compliance-as-a-Service document pdf text
Compliance-as-a-Service document pdf textCompliance-as-a-Service document pdf text
Compliance-as-a-Service document pdf text
Earthling security
 
Securiport - A Border Security Company
Securiport  -  A Border Security CompanySecuriport  -  A Border Security Company
Securiport - A Border Security Company
Securiport
 
6th Power Grid Model Meetup - 21 May 2025
6th Power Grid Model Meetup - 21 May 20256th Power Grid Model Meetup - 21 May 2025
6th Power Grid Model Meetup - 21 May 2025
DanBrown980551
 
If You Use Databricks, You Definitely Need FME
If You Use Databricks, You Definitely Need FMEIf You Use Databricks, You Definitely Need FME
If You Use Databricks, You Definitely Need FME
Safe Software
 
Domino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
Domino IQ – Was Sie erwartet, erste Schritte und AnwendungsfälleDomino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
Domino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
panagenda
 
Mark Zuckerberg teams up with frenemy Palmer Luckey to shape the future of XR...
Mark Zuckerberg teams up with frenemy Palmer Luckey to shape the future of XR...Mark Zuckerberg teams up with frenemy Palmer Luckey to shape the future of XR...
Mark Zuckerberg teams up with frenemy Palmer Luckey to shape the future of XR...
Scott M. Graffius
 
How to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptxHow to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptx
Version 1 Analytics
 
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdfHow Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
Rejig Digital
 
Domino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use CasesDomino IQ – What to Expect, First Steps and Use Cases
Domino IQ – What to Expect, First Steps and Use Cases
panagenda
 
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
angelo60207
 
Extend-Microsoft365-with-Copilot-agents.pptx
Extend-Microsoft365-with-Copilot-agents.pptxExtend-Microsoft365-with-Copilot-agents.pptx
Extend-Microsoft365-with-Copilot-agents.pptx
hoang971
 
Improving Developer Productivity With DORA, SPACE, and DevEx
Improving Developer Productivity With DORA, SPACE, and DevExImproving Developer Productivity With DORA, SPACE, and DevEx
Improving Developer Productivity With DORA, SPACE, and DevEx
Justin Reock
 
ISOIEC 42005 Revolutionalises AI Impact Assessment.pptx
ISOIEC 42005 Revolutionalises AI Impact Assessment.pptxISOIEC 42005 Revolutionalises AI Impact Assessment.pptx
ISOIEC 42005 Revolutionalises AI Impact Assessment.pptx
AyilurRamnath1
 
IntroSlides-May-BuildWithAi-EarthEngine.pdf
IntroSlides-May-BuildWithAi-EarthEngine.pdfIntroSlides-May-BuildWithAi-EarthEngine.pdf
IntroSlides-May-BuildWithAi-EarthEngine.pdf
Luiz Carneiro
 
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Safe Software
 
Data Virtualization: Bringing the Power of FME to Any Application
Data Virtualization: Bringing the Power of FME to Any ApplicationData Virtualization: Bringing the Power of FME to Any Application
Data Virtualization: Bringing the Power of FME to Any Application
Safe Software
 
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdfBoosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Boosting MySQL with Vector Search -THE VECTOR SEARCH CONFERENCE 2025 .pdf
Alkin Tezuysal
 
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
“State-space Models vs. Transformers for Ultra-low-power Edge AI,” a Presenta...
Edge AI and Vision Alliance
 
LSNIF: Locally-Subdivided Neural Intersection Function
LSNIF: Locally-Subdivided Neural Intersection FunctionLSNIF: Locally-Subdivided Neural Intersection Function
LSNIF: Locally-Subdivided Neural Intersection Function
Takahiro Harada
 
Compliance-as-a-Service document pdf text
Compliance-as-a-Service document pdf textCompliance-as-a-Service document pdf text
Compliance-as-a-Service document pdf text
Earthling security
 
Securiport - A Border Security Company
Securiport  -  A Border Security CompanySecuriport  -  A Border Security Company
Securiport - A Border Security Company
Securiport
 
6th Power Grid Model Meetup - 21 May 2025
6th Power Grid Model Meetup - 21 May 20256th Power Grid Model Meetup - 21 May 2025
6th Power Grid Model Meetup - 21 May 2025
DanBrown980551
 
If You Use Databricks, You Definitely Need FME
If You Use Databricks, You Definitely Need FMEIf You Use Databricks, You Definitely Need FME
If You Use Databricks, You Definitely Need FME
Safe Software
 
Domino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
Domino IQ – Was Sie erwartet, erste Schritte und AnwendungsfälleDomino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
Domino IQ – Was Sie erwartet, erste Schritte und Anwendungsfälle
panagenda
 

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