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 Techniques Using Lambdas and Enumerables

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
 
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
 
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
 
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 Techniques Using Lambdas and Enumerables (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
 
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 "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?"
 
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

How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAndikSusilo4
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxnull - The Open Security Community
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 

Recently uploaded (20)

How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & Application
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 

Functional Javascript Techniques Using Lambdas and Enumerables

  • 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