SlideShare ist ein Scribd-Unternehmen logo
1 von 11
JavaScript Patterns

       Part 3
Functions



● apply
   ○ highlights the true nature of functions
   ○ multiple params via []


● call
   ○ sugar for apply
   ○ single param


● invocation
    ○ sugar for apply
Functions
● First-class objects
● Local scope
● Different ways to utilize
   ○ Declarations
   ○ Expressions
        ■ Constructors
           ■ Built-in
           ■ Custom
        ■ Variables
           ■ named and anonymous
           ■ can be assigned, copied, augmented, passed, returned
Functions
Scope
 ● functions provide scope
 ● curly braces/blocks do not


Named vs. Unnamed/Anonymous
 ● named
    ○ 'name' extremely useful for debugging
    ○ 'name' needed for recursive functions
    ○ 'name' is read-only
    ○ 'name' is not standard, but mostly available
    ○ assigning a different name than the var is a bad idea
        ■ it's possible, but not properly implemented in IE
 ● anonymous
    ○ 'undefined' in IE
    ○ empty string in WebKit
Functions    


Expressions vs. Declarations




 ● declarations
    ○ part of program code (in another function or on global)
    ○ don't end with semi-colon


 ● expressions
    ○ may require semi-colon
    ○ used to create custom objects


 ● some prefer expressions over declarations
Functions


Function Hoisting


 ● remember variable hoisting?
     ○ var declarations get hoisted to top of scope
     ○ the var assignments do not


 ● there's function hoisting too!
     ○ function declaration definitions get hoisted ALONG with
       their declarations
     ○ function expression definitions are not hoisted, just the variable
       declaration
Functions
Callbacks


 ● since functions are objects they can be passed
     ○ pass anonymous functions inline
     ○ pass declaration references
     ○ make sure to guard against misuse
 ● passed callback often belongs to some object
     ○ watch out for scope issues and 'this'
     ○ if object method used as callback uses 'this'
          ■ it work as expected when not passed as callback
          ■ when used as callback 'this' will not refer to the object the
            method belongs to, it will refer to the scope it is call-backed from
          ■ solution is to also pass the object and use 'call'
Functions    


Callbacks


 ● event handlers
    ○ click, key press, mouseover, mousemove


 ● timeouts
     ○ setTimeout, setInterval


 ● great way to provide hooks for a library
Functions


Returning
 ● values, objects, or... other functions
    ○ one-time initializing
    ○ create scope for private var

Redefining
 ● overwrite function assignment inside the function
    ○ one-time initializing, private scope for var's
    ○ gotchas
        ■ function properties could be lost
        ■ re-assignment to new name will mess it up
Functions


Immediate Functions


 ● wrap chunks of code without polluting global
 ● uses a function expression
 ● executes immediately
 ● wrapped in parens OR set to var
 ● can pass in parameters
    ○ any various props
    ○ reference to global
    ○ reference to a parent application object
    ○ if more than 2, consider a configuration object
 ● can return values, functions, objects
 ● can be nested
Functions


Memoization
 ● fancy word for 'cache'


 ● functions have built-in properties, like 'length'


 ● add your own and call it 'cache'


 ● use it to store expensive data


 ● for multiple/complex stored values: serialize
     ○ gotcha: input objects with same properties

Weitere ähnliche Inhalte

Was ist angesagt?

Actor-based concurrency and Akka Fundamentals
Actor-based concurrency and Akka FundamentalsActor-based concurrency and Akka Fundamentals
Actor-based concurrency and Akka Fundamentals
Ngoc Dao
 

Was ist angesagt? (20)

Declarative JavaScript concepts and implemetation
Declarative JavaScript concepts and implemetationDeclarative JavaScript concepts and implemetation
Declarative JavaScript concepts and implemetation
 
Airbnb Javascript Style Guide
Airbnb Javascript Style GuideAirbnb Javascript Style Guide
Airbnb Javascript Style Guide
 
Pointers & functions
Pointers &  functionsPointers &  functions
Pointers & functions
 
Composite types
Composite typesComposite types
Composite types
 
JavaScript Operators
JavaScript OperatorsJavaScript Operators
JavaScript Operators
 
Javascript for Intermediates
Javascript for IntermediatesJavascript for Intermediates
Javascript for Intermediates
 
Swift, a quick overview
Swift, a quick overviewSwift, a quick overview
Swift, a quick overview
 
JavaScript operators
JavaScript operatorsJavaScript operators
JavaScript operators
 
Groovy / comparison with java
Groovy / comparison with javaGroovy / comparison with java
Groovy / comparison with java
 
JavaScript Beyond jQuery
JavaScript Beyond jQueryJavaScript Beyond jQuery
JavaScript Beyond jQuery
 
JavaScript Data Types
JavaScript Data TypesJavaScript Data Types
JavaScript Data Types
 
FRP
FRPFRP
FRP
 
Optionals by Matt Faluotico
Optionals by Matt FaluoticoOptionals by Matt Faluotico
Optionals by Matt Faluotico
 
Actor-based concurrency and Akka Fundamentals
Actor-based concurrency and Akka FundamentalsActor-based concurrency and Akka Fundamentals
Actor-based concurrency and Akka Fundamentals
 
Functional programming with Ruby - can make you look smart
Functional programming with Ruby - can make you look smartFunctional programming with Ruby - can make you look smart
Functional programming with Ruby - can make you look smart
 
Whats to come with swift generics
Whats to come with swift genericsWhats to come with swift generics
Whats to come with swift generics
 
Ruby Functional Programming
Ruby Functional ProgrammingRuby Functional Programming
Ruby Functional Programming
 
Constructor & destructor
Constructor & destructorConstructor & destructor
Constructor & destructor
 
Presentatioon on type conversion and escape characters
Presentatioon on type conversion and escape charactersPresentatioon on type conversion and escape characters
Presentatioon on type conversion and escape characters
 
Functional programming and ruby in functional style
Functional programming and ruby in functional styleFunctional programming and ruby in functional style
Functional programming and ruby in functional style
 

Andere mochten auch

Andere mochten auch (9)

Clean Code
Clean CodeClean Code
Clean Code
 
Code Kata
Code KataCode Kata
Code Kata
 
JavaScript: The Good Parts
JavaScript: The Good PartsJavaScript: The Good Parts
JavaScript: The Good Parts
 
Presentation janice baay
Presentation janice baayPresentation janice baay
Presentation janice baay
 
Presentation janice baay
Presentation janice baayPresentation janice baay
Presentation janice baay
 
Presentation janice baay
Presentation janice baayPresentation janice baay
Presentation janice baay
 
Presentation janice baay
Presentation janice baayPresentation janice baay
Presentation janice baay
 
Classic Mistakes
Classic MistakesClassic Mistakes
Classic Mistakes
 
Code Kata: String Calculator in Flex
Code Kata: String Calculator in FlexCode Kata: String Calculator in Flex
Code Kata: String Calculator in Flex
 

Ähnlich wie JavaScript: Patterns, Part 3

JavaScript: Patterns, Part 1
JavaScript: Patterns, Part  1JavaScript: Patterns, Part  1
JavaScript: Patterns, Part 1
Chris Farrell
 

Ähnlich wie JavaScript: Patterns, Part 3 (20)

JavaScript Introductin to Functions
JavaScript Introductin to FunctionsJavaScript Introductin to Functions
JavaScript Introductin to Functions
 
Object oriented java script
Object oriented java scriptObject oriented java script
Object oriented java script
 
JavaScript objects and functions
JavaScript objects and functionsJavaScript objects and functions
JavaScript objects and functions
 
Functional programming in Scala
Functional programming in ScalaFunctional programming in Scala
Functional programming in Scala
 
JavaScript: Patterns, Part 1
JavaScript: Patterns, Part  1JavaScript: Patterns, Part  1
JavaScript: Patterns, Part 1
 
Best practices for ansible
Best practices for ansibleBest practices for ansible
Best practices for ansible
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
 
Advanced PHP Simplified
Advanced PHP SimplifiedAdvanced PHP Simplified
Advanced PHP Simplified
 
funcs, func expressions, closure, returning funcs, recursion, the stack -goph...
funcs, func expressions, closure, returning funcs, recursion, the stack -goph...funcs, func expressions, closure, returning funcs, recursion, the stack -goph...
funcs, func expressions, closure, returning funcs, recursion, the stack -goph...
 
JavaScript Getting Started
JavaScript Getting StartedJavaScript Getting Started
JavaScript Getting Started
 
Swift Tutorial Part 2. The complete guide for Swift programming language
Swift Tutorial Part 2. The complete guide for Swift programming languageSwift Tutorial Part 2. The complete guide for Swift programming language
Swift Tutorial Part 2. The complete guide for Swift programming language
 
Learn To Code: Introduction to java
Learn To Code: Introduction to javaLearn To Code: Introduction to java
Learn To Code: Introduction to java
 
JavaScript - Chapter 6 - Basic Functions
 JavaScript - Chapter 6 - Basic Functions JavaScript - Chapter 6 - Basic Functions
JavaScript - Chapter 6 - Basic Functions
 
The art of readable code (ch1~ch4)
The art of readable code (ch1~ch4)The art of readable code (ch1~ch4)
The art of readable code (ch1~ch4)
 
The art of readable code (ch1~ch4)
The art of readable code (ch1~ch4)The art of readable code (ch1~ch4)
The art of readable code (ch1~ch4)
 
Object oriented programming in java
Object oriented programming in javaObject oriented programming in java
Object oriented programming in java
 
Object Oriented Programming
Object Oriented ProgrammingObject Oriented Programming
Object Oriented Programming
 
Functions
FunctionsFunctions
Functions
 
Automating with ansible (Part c)
Automating with ansible (Part c) Automating with ansible (Part c)
Automating with ansible (Part c)
 
(3) cpp procedural programming
(3) cpp procedural programming(3) cpp procedural programming
(3) cpp procedural programming
 

Mehr von Chris Farrell (7)

iOS: A Broad Overview
iOS: A Broad OverviewiOS: A Broad Overview
iOS: A Broad Overview
 
OpenGL ES on Android
OpenGL ES on AndroidOpenGL ES on Android
OpenGL ES on Android
 
Android security
Android securityAndroid security
Android security
 
Function Points
Function PointsFunction Points
Function Points
 
Software Development Fundamentals
Software Development FundamentalsSoftware Development Fundamentals
Software Development Fundamentals
 
iOS App Dev
iOS App Dev iOS App Dev
iOS App Dev
 
iOS release engineering
iOS release engineeringiOS release engineering
iOS release engineering
 

Kürzlich hochgeladen

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Kürzlich hochgeladen (20)

DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
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
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
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
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 

JavaScript: Patterns, Part 3

  • 2. Functions ● apply ○ highlights the true nature of functions ○ multiple params via [] ● call ○ sugar for apply ○ single param ● invocation ○ sugar for apply
  • 3. Functions ● First-class objects ● Local scope ● Different ways to utilize ○ Declarations ○ Expressions ■ Constructors ■ Built-in ■ Custom ■ Variables ■ named and anonymous ■ can be assigned, copied, augmented, passed, returned
  • 4. Functions Scope ● functions provide scope ● curly braces/blocks do not Named vs. Unnamed/Anonymous ● named ○ 'name' extremely useful for debugging ○ 'name' needed for recursive functions ○ 'name' is read-only ○ 'name' is not standard, but mostly available ○ assigning a different name than the var is a bad idea ■ it's possible, but not properly implemented in IE ● anonymous ○ 'undefined' in IE ○ empty string in WebKit
  • 5. Functions     Expressions vs. Declarations ● declarations ○ part of program code (in another function or on global) ○ don't end with semi-colon ● expressions ○ may require semi-colon ○ used to create custom objects ● some prefer expressions over declarations
  • 6. Functions Function Hoisting ● remember variable hoisting? ○ var declarations get hoisted to top of scope ○ the var assignments do not ● there's function hoisting too! ○ function declaration definitions get hoisted ALONG with their declarations ○ function expression definitions are not hoisted, just the variable declaration
  • 7. Functions Callbacks ● since functions are objects they can be passed ○ pass anonymous functions inline ○ pass declaration references ○ make sure to guard against misuse ● passed callback often belongs to some object ○ watch out for scope issues and 'this' ○ if object method used as callback uses 'this' ■ it work as expected when not passed as callback ■ when used as callback 'this' will not refer to the object the method belongs to, it will refer to the scope it is call-backed from ■ solution is to also pass the object and use 'call'
  • 8. Functions     Callbacks ● event handlers ○ click, key press, mouseover, mousemove ● timeouts ○ setTimeout, setInterval ● great way to provide hooks for a library
  • 9. Functions Returning ● values, objects, or... other functions ○ one-time initializing ○ create scope for private var Redefining ● overwrite function assignment inside the function ○ one-time initializing, private scope for var's ○ gotchas ■ function properties could be lost ■ re-assignment to new name will mess it up
  • 10. Functions Immediate Functions ● wrap chunks of code without polluting global ● uses a function expression ● executes immediately ● wrapped in parens OR set to var ● can pass in parameters ○ any various props ○ reference to global ○ reference to a parent application object ○ if more than 2, consider a configuration object ● can return values, functions, objects ● can be nested
  • 11. Functions Memoization ● fancy word for 'cache' ● functions have built-in properties, like 'length' ● add your own and call it 'cache' ● use it to store expensive data ● for multiple/complex stored values: serialize ○ gotcha: input objects with same properties