javascript

Introduction

You may have heard about closures. You most certainly already use them even if you don’t fully know what they are. Closures require you to know:

Three facts:

Fact One: In Javascript, you can refer to variables defined outside of the current function.

function makeCookies(){
    const secretIngredient = "coconut oil"
    function bake(chocolate){
        return secretIngredient + " and " + chocolate
    }

    return bake("white chocolate")
}

makeCookies() // coconut oil and white chocolate

Here, we can see that the inner function bake can access the variable secretIngredient, even though it was defined in the outer makeCookies function.

Fact Two: Functions can refer to variables defined in outer functions even after those outer functions returned!

Because functions are first-class objects, you can store functions inside variables and call them later on. I’ve talked about higher-order functions in a [https://dev.to/damcosset/higher-order-functions-in-javascript-4j8b](previous article)

function cookiesMaker(){
    const secretIngredient = "coconut oil"
    function bake(chocolate){
        return secretIngredient + " and " + chocolate + " chocolate."
    }

    return bake
}

const func = cookiesMaker() // Storing the function in a variable

Here, cookiesMaker is called and we store the result of that function inside a variable. If you print out the func variable right now, you would see the bake function.

The bake function uses a variable declared outside of the bake function (secretIngredient). The bake function can still remember that variable even if cookiesMaker has already returned.

func("black") // coconut oil and black chocolate.
func("white") // coconut oil and white chocolate.

How is this possible? Well, in Javascript, function values do not just store the code required to execute when they are called. They also store any references to variables they need to execute. Functions like the bake function, who refer to variables declared in their containing scopes are known as closures.

The bake function here keeps track of two variables declared in its containing scope: secretIngredient and chocolate.

When we call bake afterwards, it still remembers those two variables because there were stored in the closure.

A closure can refer to any variable or parameter in its scope. Check this out:

function cookiesBaker(cook){
    return function addSecretIngredient(secretIngredient){
        return function bakeCookie(chocolate){
            return `${cook} cooked a ${secretIngredient} ${chocolate} chocolate cookie.`
        }
    }
}

In this example, the inner function bakeCookie refers to a parameter from the outer cookiesBaker function (cook), a parameter from the outer addSecretIngredient function (secretIngredient) and a parameter from its own scope (chocolate).

const cook = cookiesBaker("Damien")

const secret = cook("peanut butter")

const result = secret("white")
// Damien cooked a peanut butter white chocolate cookie.

Here, we are taking one more step.

We return the inner function addSecretIngredient and store that in a variable. Then, we call that stored function, the result ( bakeCookie ) is stored inside another variable. Finally, we call that function. The final results, as you can see, remembers all the variables stored inside the closure.

We can also use this to make more general-purpose functions.

Let’s say we want to create a function for all cookies baked by Johnny:

const bakedByJohnny = cookiesBaker("Johnny")

bakedByJohnny("coconut oil")("black") // Johnny cooked a coconut oil black chocolate cookie.

bakedByJohnny("")("milk") // Johnny cooked a  milk chocolate cookie.

Notice that instead of declaring a variable and storing the intermediate function inside it. I can call the inner function immediately because bakedByJohnny(“coconut oil”) is returning a function!

Ok, another little example. Let’s create a function for all cookies baked by Sarah with peanut butter:

const bakedBySarahPeanutButter = cookiesBaker("Sarah")("peanut butter")

bakedBySarahPeanutButter("white")
//Sarah cooked a peanut butter white chocolate cookie.

bakedBySarahPeanutButter("black")
// Sarah cooked a peanut butter black chocolate cookie.

bakedBySarahPeanutButter("milk")
// Sarah cooked a peanut butter milk chocolate cookie.

Even though the two functions we created come from the same function definition, they are two distinct objects and both store different variables.

Note: The functions can be anonymous, like so:

let cookiesBaker = function(cook){
    return function(secretIngredient){
        return function(chocolate){
            return `${cook} cooked a ${secretIngredient} ${chocolate} chocolate cookie.`
        }
    }

This code would give the exact same results than before!

Fact Three: Closures can not only remember the variable in their containing scope, they can also update it.

Consider the following example:

const secretIngredient = function(){
    let ingredient = undefined
    return {
        changeIngredient: newIngredient => { ingredient = newIngredient },
        showIngredient: () => ingredient,
        type: () => typeof ingredient
    }
}

This function returns 3 closures. Each method in the object returned refer to a variable defined in the containing scope.

Now, let’s prove that closures can not only read outer variables, they can also update them:

let i = secretIngredient()

i.showIngredient() // undefined
i.type() // undefined

i.changeIngredient("coconut oil")

i.showIngredient() // coconut oil
i.type() // string

Tadaaaaa!

Conclusion

Closures are one of those things that you most likely use very often. You probably didn’t even know about it! Check your code and try to identify closures, get comfortable with them, and use their full powers!

Read more

Introduction

In Javascript, functions are values ( first-class citizens ). This means that they can be assigned to a variable and/or passed as a value.

let random = function(){
    return Math.random()
}

let giveMeRandom = random // assigning random to a variable

This single piece of knowledge allows us to write functional programming in this language. In functional programming, we heavily use higher-order functions.

Higher-order functions?

Higher-order functions are functions that take other functions as arguments or return functions as their results.

Taking an other function as an argument is often referred as a callback function, because it is called back by the higher-order function. This is a concept that Javascript uses a lot.

For example, the map function on arrays is a higher order function. The map function takes a function as an argument.

const double = n => n * 2

[1, 2, 3, 4].map(double) // [ 2, 4, 6, 8 ]

Or, with an anonymous function:

[1, 2, 3, 4].map(function(n){
    return n * 2
}) // [ 2, 4, 6, 8 ]

The map function is one of the many higher-order functions built into the language. sort, reduce, filter, forEach are other examples of higher-order functions built into the language.

Higher-order functions allows you to write simpler and more elegant code. Let’s look at what the code above would look like without such an abstraction. Let’s replace the map function by a loop:

let array = [1, 2, 3, 4]
let newArray = []

for(let i = 0; n < array.length; i++) {
    newArray[i] = array[i] * 2
}

newArray // [ 2, 4, 6, 8 ]

The power of composition

One of the great advantages of using higher order functions when we can is composition.

We can create smaller functions that only take care of one piece of logic. Then, we compose more complex functions by using different smaller functions.

This technique reduces bugs and makes our code easier to read and understand.

By learning to use higher-order functions, you can start writing better code.

Example

Lets try with an example. Assume we have a list of grades from a classroom. Our classroom has 5 girls, 5 boys and each of them has a grade between 0 and 20.

var grades = [
    {name: 'John', grade: 8, sex: 'M'},
    {name: 'Sarah', grade: 12, sex: 'F'},
    {name: 'Bob', grade: 16, sex: 'M'},
    {name: 'Johnny', grade: 2, sex: 'M'},
    {name: 'Ethan', grade: 4, sex: 'M'},
    {name: 'Paula', grade: 18, sex: 'F'},
    {name: 'Donald', grade: 5, sex: 'M'},
    {name: 'Jennifer', grade: 13, sex: 'F'},
    {name: 'Courtney', grade: 15, sex: 'F'},
    {name: 'Jane', grade: 9, sex: 'F'}
]

I want to know a few things about this:

  • The average grade of this classroom
  • The average grade of the boys
  • The average grade of the girls
  • The higher note among the boys
  • The higher note among the girls

We will try to use higher-order functions to get a program that is simple and easy to read. Let’s start by writing simple functions that can work together:

let isBoy = student => student.sex === 'M'

let isGirl = student => student.sex === 'F'

let getBoys = grades => (
    grades.filter(isBoy)
)

let getGirls = grades => (
    grades.filter(isGirl)
)

let average = grades => (
    grades.reduce((acc, curr) => (
        acc + curr.grade
    ), 0) / grades.length
)

let maxGrade = grades => (
    Math.max(...grades.map(student => student.grade))
)

let minGrade = grades => (
    Math.min(...grades.map(student => student.grade))
)

I wrote 7 functions, and each of them has one job, and one job only.

isBoy and isGirl are responsible for checking if one student is a boy or a girl.

getBoys and getGirls are responsible for getting all the boys or girls from the classroom.

maxGrade and minGrade are responsible for getting the greatest and lowest grade in some data.

Finally, average is responsible to calculate the average grade of some data.

Notice that the average function doesn’t know anything about the type of data it’s suppose to process yet. That’s the beauty of composition. We can re-use our code in different places. I can just plug this function with others.

Now, we have what we need to write higher-order functions:

let classroomAverage = average(grades) // 10.2
let boysAverage = average(getBoys(grades)) // 7
let girlsAverage = average(getGirls(grades)) // 13.4
let highestGrade = maxGrade(grades) // 18
let lowestGrade = minGrade(grades) // 2
let highestBoysGrade = maxGrade(getBoys(grades)) // 16
let lowestBoysGrade = minGrade(getBoys(grades)) // 2
let highestGirlsGrade = maxGrade(getGirls(grades)) // 18
let lowestGirlsGrade = minGrade(getGirls(grades)) // 9

Notice that the outer functions, average for example, always take as an input the output from the inner functions. Therefore, the only condition to composition is to make sure that the output and input match.

And because each function is responsible for only one thing, it makes our code that much easier to debug and to test.

Composition rules!

Read more

Introduction

In my last article, I gave a quick overview of the Hyperledger Composer framework to build a business network with a private blockchain technology. I used a land registry network to show how the framework works. We then used a React application to use the REST API provided.

This time, instead of using the REST API, I made a little command line application using the Javascript API. The concept is simple. You enter commands in your terminal to trigger actions ( retrieve data, create assets and/or transactions ). We will re-use the same land registry network I used in the previous article.

Continue reading Private Blockchains: Hyperledger Composer Javascript API

Read more

Introduction

Aaaaah, prototypes… How many blog posts did you read where prototypes are listed as a must-know caracteristic of the language? How many times senior developers told you about prototypal inheritance? I’ve spent quite some time avoiding to learn more deeply about this thing. I got tired of procrastinating, so I wrote this thing.

Continue reading No, not inheritance, please call me delegation…

Read more

With ES6, we were given a new tool: generators. In a normal function, there is only one entry point: the invocation of the function itself. A generator allows you to pause the execution of a function and resume it later. Generators are useful when dealing with iterators and can simplify the asynchronous nature of Javascript.

Syntax

So, how would we define a generator, compared to a normal function? You declare a generator function by using the * ( asterisk ) operator after the function keyword:

function* awesomeGenerator(){
  //code
}

To pause the execution inside the generator, we use the statement yield:

function* awesomeGenerator(){
  yield 'Hey friend' // We pause the execution here
  console.log('Back again') // When we resume, we are here
}

next() method

A generator gives you a next() method, which is used to start/resume the execution. This method returns an object with two keys:

{
  value: [ yielded value ],
  done: [ true if we reach the end]
}

Let’s see a very simple generator in action:

function* groceriesGenerator(){
  yield 'Eggs'
  yield 'Tomatoes'
  yield 'Milk'
  return 'Paper Bag'
}

const groceries = groceriesGenerator()

console.log(groceries.next()) // [1]
console.log(groceries.next()) // [2]
console.log(groceries.next()) // [3]
console.log(groceries.next()) // [4]

// [1] { value: 'Eggs', done: false }
// [2] { value: 'Tomatoes', done: false }
// [3] { value: 'Milk', done: false }
// [4] { value: 'Paper Bag', done: true }

At our first groceries.next() call, our groceriesGenerator reached our first yield statement and paused, returning the value Eggs to the caller. Our second next() resumed the execution at the second yield statement, pausing it again and returning Tomatoes

Our last next() terminates the generator, returns Paper Bag and sets done to true.

As iterators

In the introduction, I said that generators could help to implement iterators. Let’s see an example:

function* iterationGenerator( arr ){
  for( let i = 0; i < arr.length; i++ ){
    yield arr[i]
  }
}

const iterator = iterationGenerator( ['John', 'Sarah', 'Joe', 'Emily'])

let current = iterator.next()

while( !current.done ){
  console.log( current.value )
  current = iterator.next()
}

// John
// Sarah
// Joe
// Emily

In this example, you can see how the state of the generator is maintained accross invocations. Whne we resume the execution by calling next(), the variables and loops are the same.

Pass values back to generators

Finally, you can also pass a value back to a generator. Here is a example:

function* twoWayGenerator(arr){
  for( let i = 0; i < arr.length; i++ ) {
    const symbol = yield 
    console.log(`${arr[i]} ${symbol}`)
  }
}

const prices = twoWayGenerator([10, 23, 12])

prices.next()
prices.next('€')
prices.next('£')
prices.next('$')

// 10 €
// 23 £
// 12 $

Here, our first next() will not print anything because we pause the execution before the first console.log. The second next() is called with an argument. This argument is provided as the returned value of the yield statement. We store this value inside the symbol variable and use it next.

You can also force a generator to throw an error:

prices.next()
prices.throw( new Error('Invalid Amount'))

//  const symbol = yield
//                   ^
//  Error: Invalid Amount

That’s it for a quick and dirty introduction about generators. In the next article, we will go a bit deeper and explore how generators can help us control the asynchronous flow of Javascript.

Read more

Introduction

Insert another intro about functional programming…

Composition

Composition is about creating small functions and creating bigger and more complete functions with them. Think of a function as a brick, composition is how you would make those bricks work together to build a wall or a house.

You might have encoutered composition in mathematics, written like so: f(g(x)). The function f is composed with the function g of x. Or f after g equals f of g of x. After because we evaluate the functions from right to left, from the inside to the outside:

f <-- g <-- x

The output of the precedent function becomes the input of the next. x is the input of g. The output of g(x) becomes the f input.

Examples?

Ok, let’s code something then. Imagine that you are a company that is in charge of manipulating text. You receive a bunch of words, and your customers want it back in a certain way.

A client comes at you with a text and says:

I want the words shorter than 5 characters to be uppercased.

We create three functions to execute those actions. One function takes the text and return words in lowercase. The second function look for short words and upperCase them. Finally, the third recreates the text from the array received.

function words( text ){
  return String( text )
    .toLowerCase()
    .split(/\s/)
}

function shortUpper( words ){
  return words.map( word => {
    if( word.length < 5 ){
      return word.toUpperCase()
    } else {
      return word
    }
  })
}

function createText( array ){
  return array.join(' ')
}

The client sends in the text and we make our functions work:

const text = 'Hello! My name is Damien and I love Javascript. Make this exciting.'

const allWords = words(text)
const upperText = shortUpper( allWords )
const newText = createText( upperText )

//hello! MY NAME IS damien AND I LOVE javascript. MAKE THIS exciting.

Great! The client got what he wanted. The problem is: our workers have to manually take the output of the words and shortUpper functions, carry them to the next function, and turn on the function’s engine on. That’s a lot of work, can we automate this?

Cue dramatic music

Enter composition

We want the function’s outputs to be sent to the next function without having to do it ourselves. Like so:

const newText = createText( shortUpper( words( text ) ) )

//hello! MY NAME IS damien AND I LOVE javascript. MAKE THIS exciting.

We read this from left to right, but, as I mentioned earlier, we execute from the inside to the outside:

createText <-- shortUpper <-- words <-- text

We even decide to create a function for this popular demand:

function upperLessThan5( text ){
  return createText( shortUpper( words( text) ) )
}

upperLessThan5( text )
//hello! MY NAME IS damien AND I LOVE javascript. MAKE THIS exciting.

Our company has another popular demand: replacing ‘.’ by ‘!!!’ while making the first character of each word uppercase. We have some functions to handle that:

function exclamationMarks( words ){
  return words.map( word => word.replace('.', '!!!'))
}

function upperFirstChar( words ){
  return words.map( word => {
    return `${word[0].toUpperCase()}${word.substr(1)}`
  })
}

function firstCharUpperExclamation( text ){
  return createText( exclamationMarks( upperFirstChar( words( text ) ) ) )
}

firstCharUpperExclamation( text )
//Hello! My Name Is Damien And I Love Javascript!!! Make This Exciting!!!

Cool, we’re able to compose functions by combining several smaller functions!

Going nuts!

The company’s CEO couldn’t be happier. The factory transforms text very fast thanks to composing. But he wants more!

What if we had a function that took all the functions as inputs and just made composition happened by itself? We could call it compose.

The engineers gather up and brainstorm. They decide to experiment with the two products they already have. They come up with this:

function composeThreeFunctions(fn3, fn2, fn1){
  return function composed( firstValue ){
    return fn3( fn2( fn1( firstValue ) ) )
  }
}

function composeFourFunctions(fn4, fn3, fn2, fn1){
  return function composed( firstValue ){
    return fn4( fn3( fn2( fn1( firstValue ) ) ) )
  }
}

const upperLessThan5 = composeThreeFunctions( createText, shortUpper, words )
upperLessThan5( text )

//hello! MY NAME IS damien AND I LOVE javascript. MAKE THIS exciting.

const exclamationFirstCharUpper = composeFourFunctions( createText, upperFirstChar, exclamationMarks, words)

exclamationFirstCharUpper( text )

//Hello! My Name Is Damien And I Love Javascript!!! Make This Exciting!!!

Our functions takes all the functions needed as parameters. It returns a function that takes the original value as parameters and return all the functions composed in the proper order. Be careful about the order! We execute from the inside to the outside. The last function you specified will be the first executed. How do the function remembers all the functions from the original function? Closure baby!

Now, we can compose whatever we want with three or four functions. But the CEO wants something generic.

What if we need to compose only two functions? or five? ten? I don’t want an infinite amount of functions sitting in my factory. Can you create one function that just take an arbitrary number of functions and compose?

Finally, the engineers come up with the compose function:

function compose( ...fns ){
  return function composed( value ) {
    let listOfFunctions = fns.slice()
    while( listOfFunctions.length > 0 ){
      value = listOfFunctions.pop()( value )
    }

    return value
  }
}

const upperLessThan5 = compose( createText, shortUpper, words )
upperLessThan5( text )

//hello! MY NAME IS damien AND I LOVE javascript. MAKE THIS exciting.

const exclamationFirstCharUpper = compose( createText, upperFirstChar, exclamationMarks, words )
exclamationFirstCharUpper( text )

//Hello! My Name Is Damien And I Love Javascript!!! Make This Exciting!!!

The compose function takes a list of functions as a parameter. We use the rest operator (…) to gather that as an array. We return a function with the original value as parameter. Inside of this function, we create a local copy of the functions array ( how? CLOSUUUUUURE ). Then we call the last function of the array with the output of the last function. pop() returns the last element of the array and remove it from the array. The output of the last listOfFunctions element becomes the input of the next one. When our array is empty, we return the final value.

I mean, this is just amazing. Now we can go absolutely crazy.

Moar examples!!!

I’m just playing around now. But the sky is the limit.

const upperLessThan5Exclamation = compose( createText, shortUpper, exclamationMarks, words )
// OOOOOORRRR
const exclamationUpperLessThan5 = compose( createText, exclamationMarks, shortUpper, words )

// Same thing, different order

upperLessThan5Exclamation( text )
exclamationUpperLessThan5( text )
//hello! MY NAME IS damien AND I LOVE javascript!!! MAKE THIS exciting!!!
//hello! MY NAME IS damien AND I LOVE javascript!!! MAKE THIS exciting!!!

function replaceAbyE( words ){
  return words.map( word => {
    return word.replace(/a/gi, 'e')
  })
}

function replaceJavascriptWithPython( words ){
  return words.map( word => {
    if( word == /javascript/i ){
      return 'Python'
    } else {
      return word
    }
  })
}

const everything = compose( createText, shortUpper, exclamationMarks, upperFirstChar, replaceAbyE, replaceJavascriptWithPython, words )

everything( text )
//Hello! MY NEME IS Demien END I LOVE Python MEKE THIS Exciting!!!

Well, I’ll stop there. I want to see how librairies like Ramda implement composition, but this is really a fun way to write code.

Read more