SlideShare a Scribd company logo
FUNCTIONAL PROGRAMMING
TECHNIQUES
IN
REGULAR JAVASCRIPT
ABOUT ME
Pavel Klimenkov
Senior Software Developer @ Geotab Inc.
Oakville, ON, Canada
WHAT THIS TALK IS ABOUT
• Pick few ideas from functional programming
• Simplify as much as possible
• Apply in JavaScript
• PROFIT!
WHAT THIS TALK IS ABOUT
• Pick few ideas from functional programming
• Simplify as much as possible
• Apply in JavaScript
• PROFIT!
WHAT THIS TALK IS ABOUT
• Pick few ideas from functional programming
• Simplify as much as possible
• Apply in JavaScript
• PROFIT!
WHAT THIS TALK IS ABOUT
• Pick few ideas from functional programming
• Simplify as much as possible
• Apply in JavaScript
• PROFIT!
WHAT THIS TALK ISN’T ABOUT
• OOP must die, FP will save the world
• Detailed FP manual
• “A monad is just a monoid in the category of endofunctors”
WHAT THIS TALK ISN’T ABOUT
• OOP must die, FP will save the world
• Detailed FP manual
• “A monad is just a monoid in the category of endofunctors”
WHAT THIS TALK ISN’T ABOUT
• OOP must die, FP will save the world
• Detailed FP manual
• “A monad is just a monoid in the category of endofunctors”
AGENDA
•Immutability
•Simple functions
•Not that simple functions
•Combining OOP and FP
•Functors
•Monads
WHAT IS FP?
It’s a declarative programming style where all functions have
no side effects and data is readonly.
BTW, SQL is also declarative
1. IMMUTABILITY
Objects don’t change their state
Values are constants
IMMUTABILITY
• Use only read-only data
• If something needs to be changed - create new instance
instead
EXAMPLE
Convert GPS coordinates to screen points
EXAMPLE: SOURCE DATA
EXAMPLE: CONVERSION
EXAMPLE: MUTABLE DATA
EXAMPLE: IMMUTABLE DATA
EXAMPLE
Edit Entity
EXAMPLE: ENTITY CONSTRUCTOR
EXAMPLE: MUTABLE DATA
EXAMPLE: IMMUTABLE DATA
HOW TO REDUCE TEMPTATION
• Use const or let instead of var
• filter/map/reduce instead of for
• Object.freeze - to prevent object mutation
IMMUTABILITY: PROS
• Simpler code
• Less bugs
• Atomic object construction (object is either fully initialised, or doesn’t exist)
• Less temporal coupling (when order of initialisation matters)
• Simpler caching
• Thread safety*
IMMUTABILITY: CONS
• Higher CPU impact (more things to do)
• Higher memory impact (and more GC)
• Higher brain impact (OOP often comes with state)
2. SIMPLE FUNCTIONS
First class functions
Pure functions
FIRST CLASS FUNCTIONS
Can be passed as arguments
Can be assigned as values
PURE FUNCTIONS
• No side-effects
• Depend on arguments only (deterministic)
EXAMPLE: SIDE-EFFECTS
EXAMPLE: NONDETERMINISTIC
FUNCTION
EXAMPLE: DETERMINISTIC
FUNCTION
SIMPLE FUNCTIONS: PROS
• No side-effects
• Less bugs
• Simpler testing
• Simpler code
• Absolute thread safety
SIMPLE FUNCTIONS: CONS
• No side-effects
• Our job is to create side-effects
• IO and Cache are side-effects
3. NOT THAT SIMPLE
FUNCTIONS
Functions composition
Functions currying
FUNCTIONS COMPOSITION
Composition - gluing functions together
EXAMPLE: COMPOSITION
EXAMPLE: COMPOSITION
EXAMPLE: COMPOSITION
Two temporary arrays. Oh, the horror!
EXAMPLE: COMPOSITION
One temporary array. Harmony restored.
EXAMPLE: MORE COMPOSITION
EXAMPLE: MORE COMPOSITION
FUNCTIONS CURRYING
Currying - partial application of a function.
EXAMPLE: CURRYING
EXAMPLE: CURRYING
EXAMPLE: CURRYING
EXAMPLE: CURRYING
EXAMPLE: CURRYING
EXAMPLE: CURRYING
NOT THAT SIMPLE FUNCTIONS: PROS
• Flexibility in using and reusing functions
• Functions tend to be smaller
• Memoization (“Simple functions” PROS list was already too
long)
NOT THAT SIMPLE FUNCTIONS: CONS
• Sometimes code looks cryptic
• Might introduce negative performance impact
COMBINING OOP AND FP
Shell - OOP, IO, side-effects
Core - FP, logic, pure functions
Core
Shell
MAIN PRINCIPLES
• Imperative shell
• Deals with IO
• Thin layer
MAIN PRINCIPLES
• Functional core
• deals with immutable data and pure functions
• contains application logic
EXAMPLE: MOVING VEHICLES
EXAMPLE: MOVING VEHICLES
IO, shell
EXAMPLE: MOVING VEHICLES
Logic,
pure functions,
core
SHELL/CORE: PROS
• Main bugs will come from the shell, which is small
• Core is easy to test. Unit tests should be enough
• Shell is the one that needs integration tests (shell is small!)
• Command query responsibility segregation out of the box
SHELL/CORE: CONS
• Anything?
FUNCTORS
Smart containers for values
EXAMPLE: INCREMENTING A PICTURE
EXAMPLE: INCREMENTING A PICTURE
EXAMPLE: INCREMENTING A PICTURE
EXAMPLE: INCREMENTING A PICTURE
EXAMPLE: INCREMENTING A PICTURE
??? 3.png ???
FUNCTOR
• Is a container around some data,
• that knows how to apply functions to that data,
• keeping result in the container
FUNCTOR
• Container - array, async, nullable - anything
• Some data - numbers, objects, other functors - anything
• Functions are applied through map()
ARRAY IS A FUNCTOR!
PROMISE IS ALMOST A FUNCTOR!
BACK TO EXAMPLE
.png
USEFUL FUNCTORS
• Maybe
• Either
• IO
• Writer
• State
MAYBE - ALMOST LIKE NULLABLE
MAYBE - ALMOST LIKE NULLABLE*
MAYBE - ALMOST LIKE NULLABLE
MAYBE EXAMPLE
MAYBE EXAMPLE
EITHER = LEFT ♥ RIGHT
EITHER = LEFT ♥ RIGHT
EITHER = LEFT ♥ RIGHT
EITHER = LEFT ♥ RIGHT
EITHER = LEFT ♥ RIGHT
EITHER = LEFT ♥ RIGHT
EITHER ♥ RAILWAY ORIENTED
PROGRAMMING
Right
Left
f(x) g(x) h(x)
Picture and concept are shamelessly borrowed from here
TO BE HONEST…
Traditional Maybe = Just ♥ Nothing
OTHER FUNCTORS
• IO - for… IO
• Writer - for logs
• State - for… state
FUNCTORS: PROS
• Convenient control over computation
• Logic and context separation
FUNCTORS: CONS
• Steep learning curve
• Temptation to use functors for everything
SKIPPED CHAPTERS
• Applicatives
• Monoids
MONADS
MONADS ARE CURSED: EITHER YOU DON’T
GET THEM, OR YOU CANT EXPLAIN THEM
EXAMPLE: NESTED ARRAYS
EXAMPLE: NESTED MAYBE
EXAMPLE: NESTED MAYBE
MAYBE WILL BECOME A MONAD IF
MAYBE WILL BECOME A MONAD IF
MAYBE WILL BECOME A MONAD IF
NOW YOU KNOW KUNG FU MONADS
Whoa!
ARRAY WILL BECOME A MONAD IF
ECMAScript gets flatten or flatMap for arrays (soon)
BTW, PROMISE IS ALMOST A MONAD
Functional programming techniques in regular JavaScript
SUMMARY
• Immutability - everything is read-only, less bugs
• Pure functions - no side-effects, less bugs
• Composition, currying - reusing functions
• Functors - separating context and logic
• Monads - smart functors
THANK YOU!
DotsAndBrackets.com
/pasha.klimenkov
/in/pavelklimenkov
slideshare.com/pashaklimenkov
Questions?

More Related Content

PDF
Great Tools Heavily Used In Japan, You Don't Know.
PDF
Asynchronous I/O in Python 3
PDF
Perl6 meets JVM
PDF
Test::Kantan - Perl and Testing
KEY
Messaging, interoperability and log aggregation - a new framework
KEY
Erlang: TL;DR
PPTX
Server::Starter meets Java
PPTX
EhTrace -- RoP Hooks
Great Tools Heavily Used In Japan, You Don't Know.
Asynchronous I/O in Python 3
Perl6 meets JVM
Test::Kantan - Perl and Testing
Messaging, interoperability and log aggregation - a new framework
Erlang: TL;DR
Server::Starter meets Java
EhTrace -- RoP Hooks

What's hot (10)

PDF
Lessons I Learned While Scaling to 5000 Puppet Agents
PDF
Concurrency in Python
PDF
Perl6 web-app
PDF
Node.js Patterns and Opinions
PDF
"How Mozilla Uses Selenium"
PDF
Windows IOCP vs Linux EPOLL Performance Comparison
PDF
JUnit 4 Can it still teach us something? - Andrzej Jóźwiak - Kariera IT Łodź ...
PDF
Why and how Pricing Assistant migrated from Celery to RQ - Paris.py #2
PPTX
A brief to PHP 7.3
PDF
Developer-friendly taskqueues: What you should ask yourself before choosing one
Lessons I Learned While Scaling to 5000 Puppet Agents
Concurrency in Python
Perl6 web-app
Node.js Patterns and Opinions
"How Mozilla Uses Selenium"
Windows IOCP vs Linux EPOLL Performance Comparison
JUnit 4 Can it still teach us something? - Andrzej Jóźwiak - Kariera IT Łodź ...
Why and how Pricing Assistant migrated from Celery to RQ - Paris.py #2
A brief to PHP 7.3
Developer-friendly taskqueues: What you should ask yourself before choosing one
Ad

Viewers also liked (20)

PDF
[FT-11][ltchen] A Tale of Two Monads
PDF
CSS-в-JS, HTML-в-JS, ВСЁ-в-JS. Все гораздо проще, когда всё вокруг JavaScript
PDF
1 grammar preintermediate
PPTX
Браузерные API обмена данными: какие и зачем
PPTX
А готов ли ваш проект к лету?
PDF
Приёмы функционального программирования в обычном JavaScript
PPTX
Игровая физика в JavaScript
PDF
Basis.js – «под капотом»
PDF
55+1 прием для улучшения Javascript-кода / Татьяна Бабич (Simbirsoft)
PDF
Unlocking the Magic of Monads with Java 8
PDF
Monads in practice
PDF
Remote (dev)tools своими руками
PDF
Monadic Java
PDF
PDF
Category Theory for Mortal Programmers
PDF
Functional Programming in C# and F#
PDF
Vue.js - реактивный фронтенд фреймворк для людей
PDF
Monadic Java
PDF
Advanced Production Debugging
PDF
Project Jigsaw in JDK 9: Modularity Comes To Java
[FT-11][ltchen] A Tale of Two Monads
CSS-в-JS, HTML-в-JS, ВСЁ-в-JS. Все гораздо проще, когда всё вокруг JavaScript
1 grammar preintermediate
Браузерные API обмена данными: какие и зачем
А готов ли ваш проект к лету?
Приёмы функционального программирования в обычном JavaScript
Игровая физика в JavaScript
Basis.js – «под капотом»
55+1 прием для улучшения Javascript-кода / Татьяна Бабич (Simbirsoft)
Unlocking the Magic of Monads with Java 8
Monads in practice
Remote (dev)tools своими руками
Monadic Java
Category Theory for Mortal Programmers
Functional Programming in C# and F#
Vue.js - реактивный фронтенд фреймворк для людей
Monadic Java
Advanced Production Debugging
Project Jigsaw in JDK 9: Modularity Comes To Java
Ad

Similar to Functional programming techniques in regular JavaScript (20)

KEY
Message:Passing - lpw 2012
PDF
Byteman and The Jokre, Sanne Grinovero (JBoss by RedHat)
PDF
Lessons learned from building Demand Side Platform
KEY
Perl in Teh Cloud
PDF
Multithreading and Parallelism on iOS [MobOS 2013]
KEY
Zero mq logs
PPTX
Keeping MongoDB Data Safe
PDF
Booting into functional programming
PPTX
C# Async/Await Explained
PPTX
Using Apache Camel as AKKA
PDF
Working With Concurrency In Java 8
KEY
Polyglot and Functional Programming (OSCON 2012)
PPTX
Introduction to Kotlin Language and its application to Android platform
PPTX
Scala in the Wild
PPTX
Distributed Model Validation with Epsilon
PDF
Funtional Ruby - Mikhail Bortnyk
PDF
Functional Ruby
PPTX
The joy of functional programming
PDF
Using JPA applications in the era of NoSQL: Introducing Hibernate OGM
PDF
Speedment - Reactive programming for Java8
Message:Passing - lpw 2012
Byteman and The Jokre, Sanne Grinovero (JBoss by RedHat)
Lessons learned from building Demand Side Platform
Perl in Teh Cloud
Multithreading and Parallelism on iOS [MobOS 2013]
Zero mq logs
Keeping MongoDB Data Safe
Booting into functional programming
C# Async/Await Explained
Using Apache Camel as AKKA
Working With Concurrency In Java 8
Polyglot and Functional Programming (OSCON 2012)
Introduction to Kotlin Language and its application to Android platform
Scala in the Wild
Distributed Model Validation with Epsilon
Funtional Ruby - Mikhail Bortnyk
Functional Ruby
The joy of functional programming
Using JPA applications in the era of NoSQL: Introducing Hibernate OGM
Speedment - Reactive programming for Java8

More from Pavel Klimiankou (7)

PPTX
Troubleshooting .net core on linux
PPTX
Browser APIs for data exchange: types and application
PPTX
Кратчайшая история JavaScript
PPTX
What is Docker
PPTX
Что такое Docker
PPTX
Chrome Extensions
PPTX
Game physics in JavaScript
Troubleshooting .net core on linux
Browser APIs for data exchange: types and application
Кратчайшая история JavaScript
What is Docker
Что такое Docker
Chrome Extensions
Game physics in JavaScript

Recently uploaded (20)

PPTX
history of c programming in notes for students .pptx
PPTX
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
PPTX
L1 - Introduction to python Backend.pptx
PPTX
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
PDF
medical staffing services at VALiNTRY
PPTX
Embracing Complexity in Serverless! GOTO Serverless Bengaluru
PPTX
CHAPTER 2 - PM Management and IT Context
PDF
Cost to Outsource Software Development in 2025
PDF
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
PDF
Upgrade and Innovation Strategies for SAP ERP Customers
PDF
PTS Company Brochure 2025 (1).pdf.......
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
PDF
Digital Systems & Binary Numbers (comprehensive )
PDF
Design an Analysis of Algorithms II-SECS-1021-03
PDF
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
PPTX
Odoo POS Development Services by CandidRoot Solutions
PDF
Product Update: Alluxio AI 3.7 Now with Sub-Millisecond Latency
PDF
Navsoft: AI-Powered Business Solutions & Custom Software Development
PDF
iTop VPN Free 5.6.0.5262 Crack latest version 2025
PPTX
Log360_SIEM_Solutions Overview PPT_Feb 2020.pptx
history of c programming in notes for students .pptx
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
L1 - Introduction to python Backend.pptx
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
medical staffing services at VALiNTRY
Embracing Complexity in Serverless! GOTO Serverless Bengaluru
CHAPTER 2 - PM Management and IT Context
Cost to Outsource Software Development in 2025
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
Upgrade and Innovation Strategies for SAP ERP Customers
PTS Company Brochure 2025 (1).pdf.......
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
Digital Systems & Binary Numbers (comprehensive )
Design an Analysis of Algorithms II-SECS-1021-03
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
Odoo POS Development Services by CandidRoot Solutions
Product Update: Alluxio AI 3.7 Now with Sub-Millisecond Latency
Navsoft: AI-Powered Business Solutions & Custom Software Development
iTop VPN Free 5.6.0.5262 Crack latest version 2025
Log360_SIEM_Solutions Overview PPT_Feb 2020.pptx

Functional programming techniques in regular JavaScript