SlideShare a Scribd company logo
1 of 35
Download to read offline
Functional Javascript
      function(i){return i};

           Ben Nolan
About me

• New Zealander living in Munich
• Blog at bennolan.com
• Developer of Behaviour.js and Groupswiki
• I promote functional-ish javascript
Target Audience

• Intermediate javascript developers that
  haven’t used prototypes enumerable
  functions.
• People that don’t quite follow .bind and
  anonymous functions(){}
Table of Contents

• Why Functional?
• Lambdas and binding
• Enumerable functions
• Examples
• Takeaways
Why Functional?

• Many small functions - Bugs are reduced by
  this methodology
• Code is more self-descriptive, promotes
  teamwork
• Testing is simplified
Why not functional?

• Code looks obtuse to new developers
  return function(i){return this.calc(i)}.bind(this);

• Prototype’s functional extensions are slower
  than native loops. This is getting better in
  later versions of prototype.
Anonymous functions

• Also known as Lambdas
  alert(function(){
    return “hello”;
  }());


• Simply put - it’s a function that doesn’t have
  a name
Benefit of the Lambda

• Don’t have to pollute your scope with lots
  of function names.
  function mysort(x,y){return x<=>y};
  ary.sort(mysort);

  or

  ary.sort(function(x,y){return x<>y});
Benefit of the Lambda
• Functions have their own scope.
  while(true){
    var x = 5; // not locally scoped
  }

  function(){
     var x = ‘a’; // locally scoped
  }



• Easier to make idempotent functions - no
  stomping on other variables
The bind Function

• Bind is required because Javascript doesn’t
   automatically call methods in the correct
   scope
• Bind returns an anonymous function that
   calls a method in the scope of the argument
• (It’s a form of currying)
Binding to a Banana
function x(){
  alert(this);
}

x(); // [object Window]

y = x.bind('Banana!')

y(); // [string Banana!]
Binding to “this”
Wrong:

MyClass.prototype = {
  initialize : function(){
     document.body.onclick = this.onclick();
  },
  onclick : function(){
     this.doSomething();
  },
  doSomething : function(){
  }
}
Binding to “this”
Wrong:

MyClass.prototype = {
  initialize : function(){
     document.body.onclick = this.onclick;
  },
  onclick : function(){
     this.doSomething();
  },
  doSomething : function(){
  }
}
Binding to “this”
Right:

MyClass.prototype = {
  initialize : function(){
     document.body.onclick = this.onclick.bind(this);
  },
  onclick : function(){
     this.doSomething();
  },
  doSomething : function(){
  }
}
Some idioms


• Smaller functions are better.
  Less code means it’s easier to inspect and
  easier to test. Use lots of small functions.
Some idioms


• Idempotent functions are the ideal.
  ie Functions that don’t alter the dom or the
  properties of a object - they just return a
  value.
Some idioms


• Pragmatism not idealism.
  Start with dirty big functions - refactor to
  smaller nicer functions as you can.
The Enumerables

• Prototype introduces ruby-ish enumerable
  functions to javascript.
• Convert a javascript array to an enumerable
  array with the $A() function.

  $A([1,2,3]);
Enumerable Example
• Old-style javascript:
  function getInsidesOf(ary){
    var outp = new Array;
    for (i in ary){outp.push(i.innerHTML);}
    return outp;
  }

  (nb: this code alters the variable i in the global
  namespace - an easy mistake to make)
Enumerable Example

• Using functional Javascript:
  function getInsidesOf(ary){
    return $A(ary).pluck(‘innerHTML’);
  }
Cool enum. methods

• Invoke(methodName) elements in the array
  invokes methodName on each

• Pluck(propertyName) gathered from each element
  returns an array of the property
   in the array

• inGroupsOf(integer)
  eg: [1,2,3,4,5] -> [[1,2],[3,4],[5]]
Enums and lambdas

• The most powerful enum methods require a
  function as an argument.
• You can sort, filter and order with these
  tools.
Lambdas and Enum.
• Simplest example:
  return $A([1,2,3,4,5]).map(
    function(i){
      return i+1;
    }
  });

  // Returns [2,3,4,5,6]
Lambdas and Enum.
                              Create an
• Simplest example:           array with
                           enum extensions

  return $A([1,2,3,4,5]).map(
    function(i){
      return i+1;
    }
  });

  // Returns [2,3,4,5,6]
Lambdas and Enum.
• Simplest example:
  return $A([1,2,3,4,5]).map(
                  Anonymous
    function(i){ function
      return i+1;
    }
  });

  // Returns [2,3,4,5,6]
Filtering Elements

• Get an array of selected checkboxes:
  $$(‘input[type=checkbox]’).select(function(el){
    return el.selected;
  });
Filtering Elements

Get an array
of input tags

    •   $$(‘input[type=checkbox]’).select(function(el){
          return el.selected;
        });
Filtering Elements
                     Call the
                      select
                     function

•   $$(‘input[type=checkbox]’).select(function(el){
      return el.selected;
    });
Filtering Elements
                               Pass a
                           function as an
                             argument

•   $$(‘input[type=checkbox]’).select(function(el){
      return el.selected;
    });
Updating Elements

• Empty the innerHTML of all A elements:
  $$(‘a’).each(function(el){
    el.update(‘’);
  });
How I structure apps

• Use OO-style classes (class.create and
  object.extend)
• Try and use a minimum of private properties
  in my classes - introspect the dom instead
• Try and use idempotent functions
Example code

• I have a rich-text-editor written with
  Prototype.
• Browsers use different markup
        IE          Safari          Mozilla

       strong     <span style=..>     em
Example code

• Convert bolded spans to <b> tags
  $$(quot;spanquot;).each(function(el){
    if(el.getStyle('font-weight')=='bold'){
      el.convertTo(‘B’);
    }
  });
Example code

• Find an element which has the style:
  “display:block”

  return this.getAncestors().find(function(el){
    return el.getStyle('display') == 'block';
  });
Take aways

• Use many small functions that are
  idempotent
• Use enumerable functions
• Use anonymous functions liberally
• See prototypejs.org for more information

More Related Content

What's hot

Currying and Partial Function Application (PFA)
Currying and Partial Function Application (PFA)Currying and Partial Function Application (PFA)
Currying and Partial Function Application (PFA)Dhaval Dalal
 
Protocol-Oriented Programming in Swift
Protocol-Oriented Programming in SwiftProtocol-Oriented Programming in Swift
Protocol-Oriented Programming in SwiftOleksandr Stepanov
 
From object oriented to functional domain modeling
From object oriented to functional domain modelingFrom object oriented to functional domain modeling
From object oriented to functional domain modelingCodemotion
 
Protocol in Swift
Protocol in SwiftProtocol in Swift
Protocol in SwiftYusuke Kita
 
DRYing to Monad in Java8
DRYing to Monad in Java8DRYing to Monad in Java8
DRYing to Monad in Java8Dhaval Dalal
 
Advanced javascript
Advanced javascriptAdvanced javascript
Advanced javascriptDoeun KOCH
 
Uncommon Design Patterns
Uncommon Design PatternsUncommon Design Patterns
Uncommon Design PatternsStefano Fago
 
Beginning Object-Oriented JavaScript
Beginning Object-Oriented JavaScriptBeginning Object-Oriented JavaScript
Beginning Object-Oriented JavaScriptStoyan Stefanov
 
JavaScript introduction 1 ( Variables And Values )
JavaScript introduction 1 ( Variables And Values )JavaScript introduction 1 ( Variables And Values )
JavaScript introduction 1 ( Variables And Values )Victor Verhaagen
 
Functional Programming in JavaScript by Luis Atencio
Functional Programming in JavaScript by Luis AtencioFunctional Programming in JavaScript by Luis Atencio
Functional Programming in JavaScript by Luis AtencioLuis Atencio
 
Java script – basic auroskills (2)
Java script – basic   auroskills (2)Java script – basic   auroskills (2)
Java script – basic auroskills (2)BoneyGawande
 
eXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingeXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingHoat Le
 
Reactive Programming with JavaScript
Reactive Programming with JavaScriptReactive Programming with JavaScript
Reactive Programming with JavaScriptCodemotion
 
Inline function
Inline functionInline function
Inline functionTech_MX
 
Javascript basics for automation testing
Javascript  basics for automation testingJavascript  basics for automation testing
Javascript basics for automation testingVikas Thange
 

What's hot (20)

Anonymous functions in JavaScript
Anonymous functions in JavaScriptAnonymous functions in JavaScript
Anonymous functions in JavaScript
 
Currying and Partial Function Application (PFA)
Currying and Partial Function Application (PFA)Currying and Partial Function Application (PFA)
Currying and Partial Function Application (PFA)
 
Protocol-Oriented Programming in Swift
Protocol-Oriented Programming in SwiftProtocol-Oriented Programming in Swift
Protocol-Oriented Programming in Swift
 
From object oriented to functional domain modeling
From object oriented to functional domain modelingFrom object oriented to functional domain modeling
From object oriented to functional domain modeling
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
 
Protocol in Swift
Protocol in SwiftProtocol in Swift
Protocol in Swift
 
DRYing to Monad in Java8
DRYing to Monad in Java8DRYing to Monad in Java8
DRYing to Monad in Java8
 
Functions1
Functions1Functions1
Functions1
 
Typescript barcelona
Typescript barcelonaTypescript barcelona
Typescript barcelona
 
Advanced javascript
Advanced javascriptAdvanced javascript
Advanced javascript
 
Uncommon Design Patterns
Uncommon Design PatternsUncommon Design Patterns
Uncommon Design Patterns
 
Beginning Object-Oriented JavaScript
Beginning Object-Oriented JavaScriptBeginning Object-Oriented JavaScript
Beginning Object-Oriented JavaScript
 
JavaScript introduction 1 ( Variables And Values )
JavaScript introduction 1 ( Variables And Values )JavaScript introduction 1 ( Variables And Values )
JavaScript introduction 1 ( Variables And Values )
 
Functional Programming in JavaScript by Luis Atencio
Functional Programming in JavaScript by Luis AtencioFunctional Programming in JavaScript by Luis Atencio
Functional Programming in JavaScript by Luis Atencio
 
Java script – basic auroskills (2)
Java script – basic   auroskills (2)Java script – basic   auroskills (2)
Java script – basic auroskills (2)
 
eXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingeXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction Training
 
Reactive Programming with JavaScript
Reactive Programming with JavaScriptReactive Programming with JavaScript
Reactive Programming with JavaScript
 
Inline function
Inline functionInline function
Inline function
 
Function overloading
Function overloadingFunction overloading
Function overloading
 
Javascript basics for automation testing
Javascript  basics for automation testingJavascript  basics for automation testing
Javascript basics for automation testing
 

Viewers also liked

JavaScript Functions
JavaScript Functions JavaScript Functions
JavaScript Functions Reem Alattas
 
JavaScript objects and functions
JavaScript objects and functionsJavaScript objects and functions
JavaScript objects and functionsVictor Verhaagen
 
Javascript built in String Functions
Javascript built in String FunctionsJavascript built in String Functions
Javascript built in String FunctionsAvanitrambadiya
 
Things about Functional JavaScript
Things about Functional JavaScriptThings about Functional JavaScript
Things about Functional JavaScriptChengHui Weng
 
Practical Functional Javascript
Practical Functional JavascriptPractical Functional Javascript
Practical Functional JavascriptOliver Steele
 
Functional JavaScript for everyone
Functional JavaScript for everyoneFunctional JavaScript for everyone
Functional JavaScript for everyoneBartek Witczak
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScriptChris Huie
 
Javascript foundations: Function modules
Javascript foundations: Function modulesJavascript foundations: Function modules
Javascript foundations: Function modulesJohn Hunter
 
Function composition in Javascript
Function composition in JavascriptFunction composition in Javascript
Function composition in JavascriptAnand Kumar
 
Javascript inside Browser (DOM)
Javascript inside Browser (DOM)Javascript inside Browser (DOM)
Javascript inside Browser (DOM)Vlad Mysla
 
A Re-Introduction to JavaScript
A Re-Introduction to JavaScriptA Re-Introduction to JavaScript
A Re-Introduction to JavaScriptSimon Willison
 
Fuel Up JavaScript with Functional Programming
Fuel Up JavaScript with Functional ProgrammingFuel Up JavaScript with Functional Programming
Fuel Up JavaScript with Functional ProgrammingShine Xavier
 
2ndQuarter2ndMeeting(formatting number)
2ndQuarter2ndMeeting(formatting number)2ndQuarter2ndMeeting(formatting number)
2ndQuarter2ndMeeting(formatting number)Esmeraldo Jr Guimbarda
 
Lambda functions in java 8
Lambda functions in java 8Lambda functions in java 8
Lambda functions in java 8James Brown
 
Functional Programming in Java 8 - Exploiting Lambdas
Functional Programming in Java 8 - Exploiting LambdasFunctional Programming in Java 8 - Exploiting Lambdas
Functional Programming in Java 8 - Exploiting LambdasGanesh Samarthyam
 
java script functions, classes
java script functions, classesjava script functions, classes
java script functions, classesVijay Kalyan
 
TM 2nd qtr-3ndmeeting(java script-functions)
TM 2nd qtr-3ndmeeting(java script-functions)TM 2nd qtr-3ndmeeting(java script-functions)
TM 2nd qtr-3ndmeeting(java script-functions)Esmeraldo Jr Guimbarda
 
Week 5 java script functions
Week 5  java script functionsWeek 5  java script functions
Week 5 java script functionsbrianjihoonlee
 

Viewers also liked (20)

JavaScript Functions
JavaScript Functions JavaScript Functions
JavaScript Functions
 
Functions in javascript
Functions in javascriptFunctions in javascript
Functions in javascript
 
JavaScript objects and functions
JavaScript objects and functionsJavaScript objects and functions
JavaScript objects and functions
 
Javascript built in String Functions
Javascript built in String FunctionsJavascript built in String Functions
Javascript built in String Functions
 
Things about Functional JavaScript
Things about Functional JavaScriptThings about Functional JavaScript
Things about Functional JavaScript
 
Practical Functional Javascript
Practical Functional JavascriptPractical Functional Javascript
Practical Functional Javascript
 
Functional JavaScript for everyone
Functional JavaScript for everyoneFunctional JavaScript for everyone
Functional JavaScript for everyone
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
 
Javascript foundations: Function modules
Javascript foundations: Function modulesJavascript foundations: Function modules
Javascript foundations: Function modules
 
Function composition in Javascript
Function composition in JavascriptFunction composition in Javascript
Function composition in Javascript
 
Javascript inside Browser (DOM)
Javascript inside Browser (DOM)Javascript inside Browser (DOM)
Javascript inside Browser (DOM)
 
A Re-Introduction to JavaScript
A Re-Introduction to JavaScriptA Re-Introduction to JavaScript
A Re-Introduction to JavaScript
 
Fuel Up JavaScript with Functional Programming
Fuel Up JavaScript with Functional ProgrammingFuel Up JavaScript with Functional Programming
Fuel Up JavaScript with Functional Programming
 
2ndQuarter2ndMeeting(formatting number)
2ndQuarter2ndMeeting(formatting number)2ndQuarter2ndMeeting(formatting number)
2ndQuarter2ndMeeting(formatting number)
 
Lambda functions in java 8
Lambda functions in java 8Lambda functions in java 8
Lambda functions in java 8
 
Functional Programming in Java
Functional Programming in JavaFunctional Programming in Java
Functional Programming in Java
 
Functional Programming in Java 8 - Exploiting Lambdas
Functional Programming in Java 8 - Exploiting LambdasFunctional Programming in Java 8 - Exploiting Lambdas
Functional Programming in Java 8 - Exploiting Lambdas
 
java script functions, classes
java script functions, classesjava script functions, classes
java script functions, classes
 
TM 2nd qtr-3ndmeeting(java script-functions)
TM 2nd qtr-3ndmeeting(java script-functions)TM 2nd qtr-3ndmeeting(java script-functions)
TM 2nd qtr-3ndmeeting(java script-functions)
 
Week 5 java script functions
Week 5  java script functionsWeek 5  java script functions
Week 5 java script functions
 

Similar to Functional Javascript

JavaScript and UI Architecture Best Practices
JavaScript and UI Architecture Best PracticesJavaScript and UI Architecture Best Practices
JavaScript and UI Architecture Best PracticesSiarhei Barysiuk
 
What's up with Prototype and script.aculo.us?
What's up with Prototype and script.aculo.us?What's up with Prototype and script.aculo.us?
What's up with Prototype and script.aculo.us?Christophe Porteneuve
 
Java script advance-auroskills (2)
Java script advance-auroskills (2)Java script advance-auroskills (2)
Java script advance-auroskills (2)BoneyGawande
 
Composition in JavaScript
Composition in JavaScriptComposition in JavaScript
Composition in JavaScriptJosh Mock
 
JavaScript 1.5 to 2.0 (TomTom)
JavaScript 1.5 to 2.0 (TomTom)JavaScript 1.5 to 2.0 (TomTom)
JavaScript 1.5 to 2.0 (TomTom)jeresig
 
Secrets of JavaScript Libraries
Secrets of JavaScript LibrariesSecrets of JavaScript Libraries
Secrets of JavaScript Librariesjeresig
 
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and JasmineSingle Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and JasminePaulo Ragonha
 
How To Test Everything
How To Test EverythingHow To Test Everything
How To Test Everythingnoelrap
 
How to write not breakable unit tests
How to write not breakable unit testsHow to write not breakable unit tests
How to write not breakable unit testsRafal Ksiazek
 
Php my sql - functions - arrays - tutorial - programmerblog.net
Php my sql - functions - arrays - tutorial - programmerblog.netPhp my sql - functions - arrays - tutorial - programmerblog.net
Php my sql - functions - arrays - tutorial - programmerblog.netProgrammer Blog
 
Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"Fwdays
 
What's new in PHP 8.0?
What's new in PHP 8.0?What's new in PHP 8.0?
What's new in PHP 8.0?Nikita Popov
 
Ruby on Rails Intro
Ruby on Rails IntroRuby on Rails Intro
Ruby on Rails Introzhang tao
 
PHPCon 2016: PHP7 by Witek Adamus / XSolve
PHPCon 2016: PHP7 by Witek Adamus / XSolvePHPCon 2016: PHP7 by Witek Adamus / XSolve
PHPCon 2016: PHP7 by Witek Adamus / XSolveXSolve
 
jQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScriptjQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScriptGuy Royse
 

Similar to Functional Javascript (20)

JavaScript and UI Architecture Best Practices
JavaScript and UI Architecture Best PracticesJavaScript and UI Architecture Best Practices
JavaScript and UI Architecture Best Practices
 
What's up with Prototype and script.aculo.us?
What's up with Prototype and script.aculo.us?What's up with Prototype and script.aculo.us?
What's up with Prototype and script.aculo.us?
 
Java script advance-auroskills (2)
Java script advance-auroskills (2)Java script advance-auroskills (2)
Java script advance-auroskills (2)
 
JavaScript Core
JavaScript CoreJavaScript Core
JavaScript Core
 
Composition in JavaScript
Composition in JavaScriptComposition in JavaScript
Composition in JavaScript
 
JavaScript 1.5 to 2.0 (TomTom)
JavaScript 1.5 to 2.0 (TomTom)JavaScript 1.5 to 2.0 (TomTom)
JavaScript 1.5 to 2.0 (TomTom)
 
Secrets of JavaScript Libraries
Secrets of JavaScript LibrariesSecrets of JavaScript Libraries
Secrets of JavaScript Libraries
 
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and JasmineSingle Page Web Applications with CoffeeScript, Backbone and Jasmine
Single Page Web Applications with CoffeeScript, Backbone and Jasmine
 
How To Test Everything
How To Test EverythingHow To Test Everything
How To Test Everything
 
SPL, not a bridge too far
SPL, not a bridge too farSPL, not a bridge too far
SPL, not a bridge too far
 
How to write not breakable unit tests
How to write not breakable unit testsHow to write not breakable unit tests
How to write not breakable unit tests
 
Unittests für Dummies
Unittests für DummiesUnittests für Dummies
Unittests für Dummies
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
 
Php my sql - functions - arrays - tutorial - programmerblog.net
Php my sql - functions - arrays - tutorial - programmerblog.netPhp my sql - functions - arrays - tutorial - programmerblog.net
Php my sql - functions - arrays - tutorial - programmerblog.net
 
Effective PHP. Part 1
Effective PHP. Part 1Effective PHP. Part 1
Effective PHP. Part 1
 
Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"Nikita Popov "What’s new in PHP 8.0?"
Nikita Popov "What’s new in PHP 8.0?"
 
What's new in PHP 8.0?
What's new in PHP 8.0?What's new in PHP 8.0?
What's new in PHP 8.0?
 
Ruby on Rails Intro
Ruby on Rails IntroRuby on Rails Intro
Ruby on Rails Intro
 
PHPCon 2016: PHP7 by Witek Adamus / XSolve
PHPCon 2016: PHP7 by Witek Adamus / XSolvePHPCon 2016: PHP7 by Witek Adamus / XSolve
PHPCon 2016: PHP7 by Witek Adamus / XSolve
 
jQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScriptjQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScript
 

Recently uploaded

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
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfOverkill Security
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
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
 
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
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
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 SavingEdi Saputra
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
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
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
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, ...apidays
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
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
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 

Recently uploaded (20)

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
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
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
 
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
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
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
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
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...
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
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, ...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
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
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 

Functional Javascript

  • 1. Functional Javascript function(i){return i}; Ben Nolan
  • 2. About me • New Zealander living in Munich • Blog at bennolan.com • Developer of Behaviour.js and Groupswiki • I promote functional-ish javascript
  • 3. Target Audience • Intermediate javascript developers that haven’t used prototypes enumerable functions. • People that don’t quite follow .bind and anonymous functions(){}
  • 4. Table of Contents • Why Functional? • Lambdas and binding • Enumerable functions • Examples • Takeaways
  • 5. Why Functional? • Many small functions - Bugs are reduced by this methodology • Code is more self-descriptive, promotes teamwork • Testing is simplified
  • 6. Why not functional? • Code looks obtuse to new developers return function(i){return this.calc(i)}.bind(this); • Prototype’s functional extensions are slower than native loops. This is getting better in later versions of prototype.
  • 7. Anonymous functions • Also known as Lambdas alert(function(){ return “hello”; }()); • Simply put - it’s a function that doesn’t have a name
  • 8. Benefit of the Lambda • Don’t have to pollute your scope with lots of function names. function mysort(x,y){return x<=>y}; ary.sort(mysort); or ary.sort(function(x,y){return x<>y});
  • 9. Benefit of the Lambda • Functions have their own scope. while(true){ var x = 5; // not locally scoped } function(){ var x = ‘a’; // locally scoped } • Easier to make idempotent functions - no stomping on other variables
  • 10. The bind Function • Bind is required because Javascript doesn’t automatically call methods in the correct scope • Bind returns an anonymous function that calls a method in the scope of the argument • (It’s a form of currying)
  • 11. Binding to a Banana function x(){ alert(this); } x(); // [object Window] y = x.bind('Banana!') y(); // [string Banana!]
  • 12. Binding to “this” Wrong: MyClass.prototype = { initialize : function(){ document.body.onclick = this.onclick(); }, onclick : function(){ this.doSomething(); }, doSomething : function(){ } }
  • 13. Binding to “this” Wrong: MyClass.prototype = { initialize : function(){ document.body.onclick = this.onclick; }, onclick : function(){ this.doSomething(); }, doSomething : function(){ } }
  • 14. Binding to “this” Right: MyClass.prototype = { initialize : function(){ document.body.onclick = this.onclick.bind(this); }, onclick : function(){ this.doSomething(); }, doSomething : function(){ } }
  • 15. Some idioms • Smaller functions are better. Less code means it’s easier to inspect and easier to test. Use lots of small functions.
  • 16. Some idioms • Idempotent functions are the ideal. ie Functions that don’t alter the dom or the properties of a object - they just return a value.
  • 17. Some idioms • Pragmatism not idealism. Start with dirty big functions - refactor to smaller nicer functions as you can.
  • 18. The Enumerables • Prototype introduces ruby-ish enumerable functions to javascript. • Convert a javascript array to an enumerable array with the $A() function. $A([1,2,3]);
  • 19. Enumerable Example • Old-style javascript: function getInsidesOf(ary){ var outp = new Array; for (i in ary){outp.push(i.innerHTML);} return outp; } (nb: this code alters the variable i in the global namespace - an easy mistake to make)
  • 20. Enumerable Example • Using functional Javascript: function getInsidesOf(ary){ return $A(ary).pluck(‘innerHTML’); }
  • 21. Cool enum. methods • Invoke(methodName) elements in the array invokes methodName on each • Pluck(propertyName) gathered from each element returns an array of the property in the array • inGroupsOf(integer) eg: [1,2,3,4,5] -> [[1,2],[3,4],[5]]
  • 22. Enums and lambdas • The most powerful enum methods require a function as an argument. • You can sort, filter and order with these tools.
  • 23. Lambdas and Enum. • Simplest example: return $A([1,2,3,4,5]).map( function(i){ return i+1; } }); // Returns [2,3,4,5,6]
  • 24. Lambdas and Enum. Create an • Simplest example: array with enum extensions return $A([1,2,3,4,5]).map( function(i){ return i+1; } }); // Returns [2,3,4,5,6]
  • 25. Lambdas and Enum. • Simplest example: return $A([1,2,3,4,5]).map( Anonymous function(i){ function return i+1; } }); // Returns [2,3,4,5,6]
  • 26. Filtering Elements • Get an array of selected checkboxes: $$(‘input[type=checkbox]’).select(function(el){ return el.selected; });
  • 27. Filtering Elements Get an array of input tags • $$(‘input[type=checkbox]’).select(function(el){ return el.selected; });
  • 28. Filtering Elements Call the select function • $$(‘input[type=checkbox]’).select(function(el){ return el.selected; });
  • 29. Filtering Elements Pass a function as an argument • $$(‘input[type=checkbox]’).select(function(el){ return el.selected; });
  • 30. Updating Elements • Empty the innerHTML of all A elements: $$(‘a’).each(function(el){ el.update(‘’); });
  • 31. How I structure apps • Use OO-style classes (class.create and object.extend) • Try and use a minimum of private properties in my classes - introspect the dom instead • Try and use idempotent functions
  • 32. Example code • I have a rich-text-editor written with Prototype. • Browsers use different markup IE Safari Mozilla strong <span style=..> em
  • 33. Example code • Convert bolded spans to <b> tags $$(quot;spanquot;).each(function(el){ if(el.getStyle('font-weight')=='bold'){ el.convertTo(‘B’); } });
  • 34. Example code • Find an element which has the style: “display:block” return this.getAncestors().find(function(el){ return el.getStyle('display') == 'block'; });
  • 35. Take aways • Use many small functions that are idempotent • Use enumerable functions • Use anonymous functions liberally • See prototypejs.org for more information