An Introduction to Javascript and Functional Programming

An Introduction to Javascript and Functional Programming

An Introduction to Javascript and Functional Programming

I’ve always been about the bottom line. Uninterested in pseudo intellectual concepts, fancy terminology and hype. Instead, I always reach for the tools and technologies that help me ship code as soon as possible. This approach was initially productive — specifically when I was building smaller “proof of concept” applications.

Unfortunately, this approach did not scale. As I progressed as a developer I started feeling the law of diminishing return on my productivity. Setting up a project, and reaching basic functionality was fast. But the real problems started creeping up when my applications started growing in complexity. I found that as a project’s lifecycle advanced I was writing complex code. Code that I had written become harder to reason about. In order to understand it, I had to be extremely concentrated.

I had this itching feeling that a better, cleaner approach to developing software had to exist. I had heard whispers about functional programming, and how it allows developers to write more concise and elegant code. I was unknowingly exposed to functional paradigms and patterns for the first time while working with React and Redux. They both incorporated some of the principles, and I liked them. I read about FP — to my initial dismay I saw its paradigms were based on abstract mathematical concepts and that it was very prevalent in academia. Being that my goal is to ship products as fast as possible, this seemed like a counterintuitive approach to what I was trying to achieve. After 4 years in engineering school, I was pretty set on the opinion that academia only tackled theoretical problems, and was unlikely to ever help me in my day-to-day of building things.

🤔🤔🤔🤔🤔🤔🤔🤔🤔🤔🤔🤔🤔🤔🤔🤔🤔🤔🤔🤔🤔🤔🤔🤔🤔🤔🤔🤔🤔🤔🤔🤔🤔

But FP kept haunting me. Elegant solutions and paradigms were sprinkled online in all my favorite open source projects, blog posts and tutorials. I put my skeptecism aside and started delving into FP.

Although the concepts involve new jargon, and include a steep learning curve, I was amazed and really excited about this “new approach”. This series of articles shares my learning experience, and aims at extracting and summarizing the pearls of FP which enable a cleaner, more concise development experience. I will attempt to build an intuitive understanding of the patterns I discuss and frame the problems and the provided solutions as simply as possible, overstepping unnecessarily complex definitions. Learning FP has a reputation for being a bit daunting, but by breaking down the concepts into smaller bits, we will make the ideas easier to digest.

The main difference in FP in comparison to other programming paradigms is a declarative approach (FP) versus an imperative one. Before we dive into formal definitions, let’s explore the differences by looking at an example.


Imperative

// triple the value of every element in a given array
const triple = (arr) => {
  let results = []
  for (let i = 0; i < arr.length; i++){
    results.push(arr[i] * 3)
  }
  return results
}

// sum all the elements in a given array const sum = (arr) => { let result = 0 for (let i = 0; i < arr.length; i++){ result += arr[i] } return result }

Imperative functions in the wild

Does this code seem evil? It should! What are the similarities between the methods above?

  1. The main complexity of this code snippet derives from the fact that instead of telling the computer what we want it to do, we are instructing it on how to do it. Code that tells the computer how to operate — ie. go to the array at index i and mutate or swap a value is called imperative code.
  2. This code isn’t readable (😱😱😱). This is a toy example, but as your program grows and your functionality becomes more sophisticated, using for loops like this creates code that is non trivial, and requires our brain to analyze the inner working of the loop while keeping track of indexes, variables and more. Imperative code increases the cognitive load when reading, and over time makes it easier to faulter in reasoning and logic.

Declarative

Let’s rewrite this snippet of code, but in a declarative manner.

// triple the value of every item in a given array
const triple = (arr) => arr.map((currentItem) => currentItem * 3)

// sum all the elements in a given array const sum = (arr) => arr.reduce((prev, current) => prev + current, 0)

.map? .reduce? What is this black magic?

First off, I promise that given the same input, these two methods produce the same output every single time.

A quick aside on the declarative snippet -

.map()is a method accessible from every array in JS. The .map() method creates a new array with the results of calling a provided function on every element in the calling array.

.reduce() is a method that applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.

Don’t fret about these just yet. We’re going to explore these handy array-native methods in depths in upcoming posts. But it is clear that the declarative snippet is more concise than the imperative one. It’s also a lot easier to read. Instead of instructing the program on which indexes I want it to access etc, I am simply supplying an expression to .map() and .reduce() (an anonymous function in our case) which tells the program what I want it do to every element in the array.

This declarative approach is going to serve us well across the board by:

  1. Learning and using patterns in your code that are well-known, understandable, and proven to keep away the mistakes that make code harder to understand.

2. Composing shorter, expressive and concise code. After all, the less code we write the less we have to debug.

Most importantly, these tools and paradigms are going to help us achieve our (my) ultimate goal of shipping products faster. Check out the next post, where we discuss functions in JS, why they are special and how their characteristics enable functional programming.


Javascript and Functional Programming — Pt.2 : First Class Functions

Welcome to the Upside Down

Before we get started, there’s something you need to know … If you’ve ever programmed in JS you’ve probably used FP patterns before! These patterns and paradigms have been there all along, we just haven’t been able to see them properly. We are going to start from the familiar and explore new territory. Things may get a bit … well … strange. But fear not! Together we will survive!


First Class Functions

In Javascript, functions are first class objects. Like I mentioned earlier, we don’t like cryptic terminology, so let’s explain. According to the Mozilla developer glossary:

A programming language is said to have First-class functions when functions in that language are treated like any other variable. For example, in such a language, a function can be passed as an argument to other functions, can be returned by another function and can be assigned as a value to a variable.

Functions as constants

In the following example we will declare a const and assign it an anonymous arrow functions.

After the initial assignment constFunction is a constant with a value of a function. We verify that by logging the constFunction variable in the Chrome inspector. Because constFunction is a function we can also invoke it.


Functions as values of keys of an object

Now that we understand that variables can hold functions, let’s demonstrate a function as a value of a key in an object. This should be familiar for anyone who has done any object oriented programming before.

const functionAsObjectProperty = {
    print: (value) => console.log(value)
};

functionAsObjectProperty.print("mic check"); // "mic check"

Functions as array items

When functions are first class objects we can pass them as data to an array, just like any other data type. Let’s use the Chrome console and check this out.


Higher order functions

Now that we’ve warmed up, let’s get to the interesting stuff :) JS developers see functions that accept other functions as arguments on a daily basis. If you’re coming from a language that doesn’t support FP this should seem a bit weird 😳😳😳😳😳😳😳 Let’s acquaint ourselves with this concept by looking at some examples.

An asynchronous function that accepts a callback function.

const jsonfile = require('jsonfile')

const file = '/tmp/data.json' const obj = {name: 'JP'}

const errorLoggerFunction = (err) => console.error(err);

jsonfile.writeFile(file, obj, errorLoggerFunction)

errorLoggerFunction is defined as a function with the ES6 arrow syntax

We’re using the jsonfile npm module in this example for the _writeFile m_ethod. The third parameter that writeFile is expecting is a function. When the jsonfile.writeFile method executes it will either succeed or fail. If it fails it will execute the errorLoggerFunction. Alternatively, we could have gone for a more terse syntax, and dropped the named function:

const jsonfile = require('jsonfile')

const file = '/tmp/data.json' const obj = {name: 'JP'}

jsonfile.writeFile(file, obj, (err) => console.error(err))

It’s an anonymous function because we didn’t name it

setTimeout

const timeout = () => {
    setTimeout(() => alert("WoW"), 1000);
}

Classic callback example

This example shows the built in asynchronous setTimeout method which accepts 2 arguments. Let’s formalize this a little bit and explain the setTimeout function in functional programming terms.

Let’s start by reading the signature of the function. We can observe that the number of arguments that setTimeout takes is two. In functional programming the number of arguments a function takes is called its Arity, from words like unary, binary, ternary etc. So we can say that setTimeout is of arity 2, or equivalently say that is a binary function.

The arguments that setTimeout expects is a function and a time interval to wait before executing the given function. Hmmm … another function that accepts a function as input?

In functional programming this is so common that these types of functions even have a name! They are called higher order functions.

A higher order function is a function that takes a function as an argument, or returns a function.

There you go. Now you can drop this term low key in any random conversation at work / with friends and sound like a boss! 😂😂😂

const add = (x,y) => x + y;
const subtract = (x,y) => x - y;
const multiply = (x,y) => x * y;

const arrayOfFunctions = [add, subtract, multiply];

arrayOfFunctions.forEach(calculationFunction => console.log(calculationFunction(1,1))); // 2 0 1

On line 5 we are declaring an array of functions. We are then using the forEach method to iterate over the array. forEach is a natively supported ES6+ function, that accepts a function to execute on every item in the array. Therefore, forEach is also a higher order function!

Our forEach accepts an anonymous function as input. forEach will iterate over the array and implicitly access the current item in the array and call it getCalculation. It is worth noting that forEach implicitly accesses array elements, in comparison to how we would have accessed the current element if we had used a regular for loop — ie. arrayOfFunctions[i]. Every item in our array is a function, therefore we invoke getCalculation with the arguments that it is expecting.

Fantastic. This example illustrates that functions in functional programming can be passed into arrays (lists) just like any other data type. Functions can go anywhere!

Now let’s build our own higher order function!

const addWrapper = () => (x,y) => x + y;

const add = addWrapper();

const sum1 = add (1,2); // 3

// Or we could do it like this

const sum2 = addWrapper()(4,4); // 8 view raw functionThatReturnsFunction.js hosted with ❤ by GitHub

The addWrapper function returns a simple addition function when called. By invoking the result of the addWrapper function and supplying it two arguments, we have access to the anonymous addition function.

We could get even crazier with our level of indirection and write a function that returns a function, that in turn returns its own function!

const bankStatement =
      name =>
        location =>
          balance =>
            Hello ${name}! Welcome to the bank of ${location}. Your current balance is ${balance};

const statementExpectingLocation = bankStatement("Omer"); const statementExpectingBalance = statementExpectingLocation("NYC"); const bankStatementMsg = statementExpectingBalance("100 million"); // wishful thinking?

console.log(bankStatementMsg); // Hello Omer! Welcome to the bank of NYC. Your current balance is 100 million

// We could also call the function with all the arguments up front const msg = bankStatement("Jeff Bezos")("Silicon Valley")("97.7 billion"); console.log(msg); // Hello Jeff Bezos! Welcome to the bank of Silicon Valley. Your current balance is 97.7 billion

I hope you like curry!

This is a very powerful pattern in functional programming. We will explore it in depth in the coming posts when we talk about currying and partial applications.

First class functions are the cornerstones of any functional programming language. The main point that you should take away from our discussion about first class functions is that functions can be assigned as constants, variables, placed as array elements and even set as values of keys on an object. Additionally, (and most importantly ?!) functions can be returned to and from functions —** just like any other data type!**


Javascript and Functional Programming — Pt. 3: Pure Functions

Purity

Motivation

So many of our bugs are rooted in IO related, data mutation, side effect bearing code. These creep up all over our code base — from things like accepting user inputs, receiving an unexpected response via an http call, or writing to the file system. Unfortunately, this is a harsh reality that we should grow accustomed to dealing with. Or is it?

What if I told you, that we could minimize the parts of our code which executed the critical / volatile bits of our program? We could enforce (by convention) that the large majority of our code base would be pure, and limit IO related / side effect bearing code to a specific part of our codebase. This would make our debugging process a lot easier, more coherent and easier to reason about.

So, what is this mythical pure function? A pure function has two main characteristics:


1. A pure function is deterministic. This means, that given the same input, the function will always return the same output. To illustrate this as a function in mathematical terms (this will be quick!) it is a well defined function. Every input returns a single output, every single time.

![Javascript and Functional Programming ](Javascript and Functional Programming "Javascript and Functional Programming ")


A pure function

const add = (x, y) => x + y // A pure function

add is a pure function because it’s output is solely dependent on the arguments it receives. Therefore, given the same values, it will always produce the same output.

How about this one?

const magicLetter = '*'
const createMagicPhrase = (phrase) => ${magicLetter}abra${phrase}

Something about this one is fishy…. The createMagicPhrase function is dependent on a value which is external to its scope. Therefore, it is not pure!


An impure function

const fetchLoginToken = externalAPI.getUserToken

Is fetchLoginToken a pure function? Does it return the same value every single time? Absolutely not! Sometimes it will work — sometimes the server will be down and we will get a 500 error — and at some point in the future the API may change so that this call is no longer valid! So, because the function is non-deterministic, we can safely say that it is an impure function.


2. A pure function will not cause side effects. A side effect is any change in the system that is observable to the outside world.

const calculateBill = (sumOfCart, tax) => sumOfCart * tax

Is calculateBill pure? Definitely :) It exhibits the two necessary characteristics:

  • The function depends only on its arguments to produce a result
  • The function does not cause any side effects

The Mostly Adequate Guide states that side effects include, but are not limited to:

  • changing the file system
  • inserting a record into a database
  • making an http call
  • mutations
  • printing to the screen / logging
  • obtaining user input
  • querying the DOM
  • accessing system state

Why should our functions be pure?

Readability -> Side effects make our code harder to read. Since a non pure function is not deterministic it may return several different values for a given input. We end up writing code that needs to account for the different possibilities. Let’s look at another http based example:

async function getUserToken(id) {
  const token = await getTokenFromServer(id);
  return token;
}

This snippet can fail in so many different ways. What if the id passed to the getTokenFromServer was invalid? What if the server crashed and returned an error, instead of the expected token? There are a lot of contingencies that need to be planned for, and forgetting one (or several!) of them is very easy.

Additionally, a pure function is easier to read, as it requires no context. It receives all of its needed parameters up front, and does not talk / tamper with the state of the application.

Testability -> Because pure functions are deterministic by nature, writing unit tests for them is a lot simpler. Either your function works or it doesn’t 😁

Parallel Code -> Since pure functions only depend on their input, and will not cause side effects, they are great for scenarios where parallel threads run and use shared memory.

Modularity and Reusability -> Think of pure functions as little units of logic. Because they only depend on the input you feed them, you can easily reuse functions between different parts of your codebase or different projects altogether.

Referential Transparency -> This one sounds so complicated 🙄🙄 When I first read the title I wanted a coffee break! Simply put, referential transparency means that a function call could be replaced by its output value, without changing the overall behavior of our program. This is mostly useful as a framework of thought when creating pure functions.


It’s pure and all…. but does it do anything?

It’s important to note that although pure functions offer a ton of benefits, it’s not realistic to only have pure functions in our applications. After all, if we did our application would have no side effects, thus not produce any observable effects to the outside world. That would be pretty boring 😥😥😥. Instead we will try to encapsulate all of our side effects to specific parts of our codebase. That way, assuming we have written unit tests for our pure functions and know they are working, if something breaks in our app, it will be a lot easier to track down.


Let’s get pure

Let’s conclude our discussion by converting the following non pure function to pure. This is a contrived example, but demonstrates how we can easily refactor unpure code to pure.

let a = 4;
let b = 5;
let c = 6;
const updateTwoVars = (a) => {
    b++;
    c = a * b;
}

updateTwoVars(a); console.log(b,c); // b = 6, c = 24

Let’s start by reviewing why this function is unpure. Our function is unpure because it depends on a and b, which are external to its scope. In addition, it is also directly mutating (changing) the values of the variables. The quickest way to refactor this function is

  • First ensure that all the variables that the function depends on are passed as arguments
  • Instead of mutating (manipulating) b and c, we can return new values which will reflect the new values.
let a = 4;
let b = 5;
let c = 6;
const updateTwoVars = (a, b, c) => [b++, a * b];

const updateRes = updateTwoVars(a,b,c); b = updateRes[0] c = updateRes[1]

Summary

We’ve covered a lot of the benefits of transitioning our code base to include more pure functions. It makes our code easier to reason about, test, and most importantly more predictable. Remember, pure functions are not about completely ridding our code base of side effects. It’s about constraining them to a definitive location and eliminating as much of them as possible. This approach will justify itself many times over, when your programs start growing in size and complexity.


Javascript and Functional Programming: Currying (Pt.4)

Currying is when we call a function with fewer arguments than it expects. In turn, the invoked function returns a function that takes the remaining arguments.

const magicPhrase = 
 (magicWord) => 
  (muggleWord) => 
    magicWord + muggleWord

We could then invoke this function with the following pattern

Call it maaagic

Writing functions that return functions, that in turn return some output (possibly another function!) can get quite cumbersome. Luckily we have functional JS helper libraries like Ramda and lodash which provide us with utility methods such as curry. The curry utility wraps normally declared functions and transforms them into a series of one-argument functions. So we could convert the previous code to:

import _ from "lodash"

const magicPhrase = _.curry((magicWord, muggleWord) => magicWord + muggleWord)

const muggleWordAccepter = magicPhrase("Abra kedabra ")

muggleWordAccepter("dishwasher")

Another example would be a revamped implementation of our favorite add function

import _ from "lodash"

const addFunction = _.curry((a, b) => a + b)

const addOne = add(1)

addTen(1)

So we are essentially, “pre loading” the add function with the first variable. Our function has the ability to remember the first value passed thanks to JS closure.


Why You Should Care About Currying

  1. Currying gives us the ability to compose terse, concise and reusable functions.

2. We use these functions as clean, testable units of logic to compose the more logically complex parts of our programs.

3. With currying, any function that works on single elements can be converted into a function that works on arrays (lists), simply by wrapping it with map.

const getObjectId = (obj) => obj.id // works on single object

const arrayOfObjects = [{id: 1}, {id: 2}, {id: 3}, {id: 4}]

const arrayOfIDs = arrayOfObjects.map(getObjectId)

BAM! Our function that worked on single elements can work on arrays!


Examples

The only real way to get familiar with these concepts is to practice :) Let’s get to it. We shall start with one more example of converting a function that operates on a single element to a function that operates on an array.

const getFirstTwoLettersOfWord = (word) => word.substring(0,2)

// We can convert it, by wrapping it in the map method

["aabb", "bbcc", "ccdd", "ddee"].map(getFirstTwoLettersOfWord)

The next example comes out of the amazing Mostly Adequate guide, with a small ES6 refactors :)

Let’s refactor the max function so that it won’t reference any arguments.

arr = [2,4,6,8,9]

// LEAVE BE: const getMax = (x, y) => { return x >= y ? x : y; };

// REFACTOR THIS ONE: const max = (arr) => { return arr.reduce((acc, x) => { return getMax(acc, x); }, -Infinity); };

const max = arr.reduce(getMax, -Infinity)

Let’s wrap the native JS slice method so that it functional and curried.

import _ from "lodash"

const arr = ["barney", "fred", "dave"]

arr.slice(0, 2) // ["barney", "fred"]

const slice = _.curry((start, end, arr) => arr.slice(start, end)); const sliceWithSetIndexes = slice(0,2)

sliceWithSetIndexes(arr) // ["barney", "fred"]

Summary

We’ve seen several examples where we curry JS functions. Currying refers to the process of transforming a function with multiple arity (arguments accepted) into the same function with less arity. It utilizes JS closure to remember the arguments used in the previous invocations. Currying twists functions around so that they can work more naturally together. Its biggest advantage is that it easily allows for function composition, which we will explore in depth in the next post!


Learn More

10 JavaScript array methods you should know

Introducing TensorFlow.js: Machine Learning in Javascript

Machine Learning in JavaScript with TensorFlow.js

5 ways to build real-time apps with JavaScript

Full Stack Developers: Everything You Need to Know

5 Javascript (ES6+) features that you should be using in 2019

The Complete JavaScript Course 2019: Build Real Projects!

JavaScript: Understanding the Weird Parts

Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)

The Full JavaScript & ES6 Tutorial - (including ES7 & React)

Originally published by Omer Goldberg at https://hackernoon.com

javascript web-development

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Hire Web Developer

Looking for an attractive & user-friendly web developer? HourlyDeveloper.io, a leading web, and mobile app development company, offers web developers for hire through flexible engagement models. You can **[Hire Web...

Why Web Development is Important for your Business

With the rapid development in technology, the old ways to do business have changed completely. A lot more advanced and developed ways are ...

Important Reasons to Hire a Professional Web Development Company

    You name the business and I will tell you how web development can help you promote your business. If it is a startup or you seeking some...

Hire Dedicated eCommerce Web Developers | Top eCommerce Web Designers

Build your eCommerce project by hiring our expert eCommerce Website developers. Our Dedicated Web Designers develop powerful & robust website in a short span of time.

How long does it take to develop/build an app?

This article covers A-Z about the mobile and web app development process and answers your question on how long does it take to develop/build an app.