Categories
Functional Javascript React

Functional JavaScript — Benefits

JavaScript is partly a functional language.

To learn JavaScript, we got to learn the functional parts of JavaScript.

In this article, we’ll look at how to use the functional programming features in JavaScript.

Functional Programming Benefits

Functional programming has various benefits.

This is why it’s being adopted into programming languages like JavaScript.

Pure Functions

One benefit of functional programming is that we define pure functions in our code.

A pure function returns the same output if we pass in the same input to it.

For instance, we can write:

const square = (value) => value ** 2;

We get the value and we return the square of it.

This doesn’t change regardless of what happens outside.

The benefit is that pure functions can easily be tested.

We can just check the output after giving it some input.

Since it doesn’t depend on anything outside, we can check for it easily.

We can check the returned value by writing something like:

square(2) === 4

Reasonable Code

It’s easy to read the code since the code for the function all reside inside the function.

For example, if we have:

const square = (value) => value ** 2;

All we did is square the number which is passed in.

There’s nothing outside, so we can look at it easily.

Parallel Code

Since pure functions don’t depend on any values outside the function, we don’t have to worry about synchronize our function’s value with something outside.

If we have global values, then we may have to do something like this:

let global = "something"
let foo = (input) => {
  global = "somethingElse"
}

let bar = () => {
  if (global === "something") {
    //...
  }
}

We’ve to check the value for the global variable before doing something.

With pure function, we don’t have to do that since there are no external dependencies.

Cachable

Pure functions always return the same output for the given input.

So we can cache the function outputs easily.

We just use the input as the key and the output as the value.

We can just look up the value from the cache.

With caching, we can increase the speed of our code.

For example, we can keep a cache with an object:

const cache = {
  1: 2,
  3: 4,
  //...
}

Then we can check or the cached value by writing:

const value = cache.hasOwnProperty(input) ?
  cache[input] :
  cache[input] = longRunningFunction(input)

We check for the cached value before we run the longRunningFunction .

Pipelines and Composable

We can compose pure functions easily.

We just pass in the return value of one pure function to another pure function.

For example, we can write:

const foo = (a) => {
  return a * 2;
}

const bar = (b) => {
  return b * 3;
}

We can compose the functions by writing:

foo(bar(100));

It looks like a mathematical function and it’s a mathematical function.

Conclusion

Functional programming has various benefits.

We can run code in parallel easily since we don’t have to synchronous code.

Also, we can compose functions easily.

They’re also easier to read and test.

Categories
Functional Javascript

Functional Programming Concepts Used in React

React is a popular library for creating web apps and mobile apps.

In this article, we’ll look at how to use functional programming features in our React app.

First-Class Objects

One big functional programming feature included with JavaScript is that functions are objects like everything else.

This way, we can set them as property values, assign them variables, and pass them in as arguments.

For instance, if we have:

const add = (a, b) => a + b;

Then we can create a function by writing:

const log = func => (...args) => {
  console.log(...args);
  return func(...args);
}

Then we can use log as follows:

const add = (a, b) => a + b;
const logAdd = log(add);
logAdd(1, 2);

And we can use logAdd to create it.

log is a higher-order function since it takes a function as an argument.

It also returns a function that can be called with its own arguments.

We pass in the add function to log to return a function.

Then we can call it by passing in arguments to the returned function.

Pure Functions

Pure functions are functions that don’t commit side effects and just return something.

This means they don’t change anything outside the function.

Impure functions are harder to debug because they change things outside a function.

For instance, if we have:

const add = (a, b) => a + b

Then that’s a pure function since it only returns something and does nothing else.

On the other hand, the following isn’t a pure function:

let sum;
const add = (a, b) => {
  sum = a + b;
  return sum;
}

since it changes the value of sum which is outside the function.

Immutability

Immutable data is another functional programming feature.

It’s good because it reduces the chances of surprise changes to data.

Since we can’t accidentally change data, we don’t have to worry about surprises.

Some things change data. For instance, the push method of an array changes the existing array.

For example, we can write:

arr.push(3)

Then we add 3 as the last value of arr .

On the other hand, if we use the spread operator, then we don’t change the existing array:

const newArr = [...arr, 3];

We assigned a new array with the spread values of arr and 3 to newArr .

Currying

Currying is the process of converting a function that takes multiple arguments into a function that takes one argument at a time.

For instance, if we have the following:

const add = (a, b) => a + b

We write:

const add = a => b => a + b

With the 2nd add function, we call it by writing:

const sum = add(1)(2);

It’s a convenient way to reuse the function that’s returned by add multiple times.

So we can write:

const addOne = add(1);
const sum1 = addOne(2);
const sum2 = addOne(3);

Composition

The composition is the concept of combining multiple functions to do more advanced or complex things.

For instance, we can have:

const add = (a, b) => a + b
const cube = x => x ** 3

Then can combine them by writing:

const cubed = cube(add(1, 3));

We call add and then we call cube on the returned result.

Functional Programming and React

We use functional programming to React to nest components, and also for creating higher-order components.

Higher-order components return a new component after passing in a component into them.

Also. hooks can be composed.

We can pass a function into the returned function in the useState hook to update an existing value with the new one for example.

Conclusion

Functional programming is important in React projects.

We’ll use it a lot to create nested components, higher-order functions, hooks, and more.

Categories
Functional Javascript

Javascript Functional Programming Features — Closures and Functions

JavaScript is an easy to learn programming language. It also uses lots of functional programming features that make our lives easier.

In this article, we’ll look at some functional programming features that are related to functions.

Closure

A closure is a function that’s inside a function that can access the items of the outer function.

It’s used to hide items from the outside while letting the inner function access the items in the outside function.

In JavaScript, closures are created every time a function is created at function creation time.

An example of a closure is the following:

const foo = () => {
  let x = 1;
  return () => x;
}

In the code above, we have the foo function which has the variable x defined inside. It also returns a function that returns x defined within foo itself.

This is what closures are good for. They let us access items from the outside from within the inner function.

Statelessness

Stateless programming is a paradigm where operations that we implement aren’t sensitive to the state of the computation. This means that all data used in an operation are passed as inputs of the operation.

And data used by whatever operations invoked that operation is passed back as outputs.

For instance, pure functions don’t change the state of the environment. If we have a function like:

const add = (a, b) => a + b;

It doesn’t change the state of the environment since it’ just takes the arguments that are passed in and then returns a value.

Statelessness goes hand in hand with pure functions since they don’t commit side effects, and side effects are designed to change the state of the program.

Composition

The composition is the combination of operations that let us break down our problems into small pieces.

With each small piece, we can build our solution to the bigger problem. We can solve small problems easily, but we can’t solve big problems all at once.

For instance, if we have pure functions, then they are composed. For instance, we can call the add function we have above repeated to get the total that we want to get for example.

With the add , function, we can compose it as follows:

const result = add(add(1, 2), 3);

In the code above, we first call add(1, 2) to get 3, then with that we call add(3, 3) to get 6 after the 3 is returned.

Any pure function can be composed easily since they’re stateless and don’t commit any side effects.

Other operations like arithmetic operations, boolean operations, are all composable since we can invoke them one after the other add they all return a new value instead of mutating the existing value.

Curry

Currying is the process of taking a function with multiple arguments and turning it into a series of functions each with only one argument.

For instance, we can create a multiplication function that each takes 3 numbers and then after calling it 3 times with one argument, returns the product of 3 numbers.

We can write the following to get that:

const curryMultiply = x => y => z => x * y * z;
const result = curryMultiply(1)(2)(3);

Then we get 6 since we first called it with 1, returns a function that returns a function to multiply 1 by y and z .

Then we call that returned function with 2, which returns a function that has the parameter z and then multiplies 1 by 2 and z .

Finally, we called that function with 3 so that we get the final product, which is 6.

Lambda

Lambda expressions are expressions that creates functions. In JavaScript, we have lambdas since functions are first-class. They’re treated like any other object within a program.

Lambdas in JavaScript are traditional or arrow anonymous or named functions that are used as parameters within a function as an array instance’s map method.

For instance, the following piece of code has a lambda function:

const arr = [1, 2, 3].map(a => a * 3);

In the code above, a => a * 3 is the lambda function. Lambdas can also be named functions, for instance, we can write:

const arr = [1, 2, 3].map(function triple(a) {
  return a * 3;
});

The triple function in the code above is a lambda function.

Conclusion

Closures let inner functions access the scope of the outer function. It’s useful for encapsulating data within a function.

Currying converts a function from multiple arguments to multiple functions that take one argument each.

Function composition is invoking multiple operations that can be combined to do one complex operation.

Statelessness is the avoidance of changing state. This makes composition easy.

Lambdas are functions that are passed in as parameters. They’re often used for callbacks.

Categories
Functional Javascript

Javascript Functional Programming Features — Functions

JavaScript is an easy to learn programming language. It also uses lots of functional programming features that make our lives easier.

In this article, we look at the functional programming characteristics of JavaScript functions.

High Order Functions

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

This means that JavaScript code can take callbacks or return functions, for example.

Examples of higher-order functions include the array instance’s map method, which we can call by writing something like the following code:

const arr = [1, 2, 3].map(a => a * 2);

In the code above, we called the map method with the callback functiona => a * 2 ,

Then the map method will call the callback to map each entry from its original value to a new value by doubling each entry, add each mapped entry in a new array and return the new array.

There’re many other array instance methods that take callbacks, include some , every , find , findIndex , filter etc.

We can create a function that returns a function by writing something like:

const returnAdd = () => (a, b) => a + b;
const result = returnAdd()(1, 2);

In the code above, we have the returnAdd function, which returns a function that adds 2 numbers together.

Then we can call the returned function to add 2 numbers by first calling the returnAdd function to return the function to add the numbers, then call the returned function to add the numbers and return the sum.

Therefore, result should be 3 in the example above.

First-Class Function

First-class functions are functions that are treated like any other object. They can be stored in variables, passed around, returned from other functions, and hold their own properties.

As we can see from the previous section, functions can be passed into another function and functions can also be returned as arguments in a function.

In addition, they can also have properties. For instance, we can set properties on a function by writing something like the following:

const foo = () => {};
foo.bar = 1;

In the example above, we have the foo function defined in the first line. Then we create the bar property on the foo function and then set its value to 1.

When we log the value of foo.bar , we should see that foo.bar is 1.

As we can see functions are just like any object in that they can have their own properties.

This is more useful for constructor functions when we need to create static properties of methods.

For instance, if we have the following constructor function:

function Person(name) {
  this.name = name;
}

Then we can define a static method for it as follows:

Person.greet = () => console.log('hello');

Now we have a static greet method, which we can call on Person . Then we can call it as follows:

Person.greet();

And we see that 'hello' is logged in the console.

The same thing can be done to add properties to the function as we saw from the previous example.

Since JavaScript classes are just syntactic sugar on top of constructor functions. We can define static members of JavaScript classes the same way as we did with constructor functions.

For instance, if we have the following class:

class Person {
  constructor(name) {
    this.name = name;
  }
}

Then we can define a static method on it as follows:

Person.greet = () => console.log('hello');

Recursion

Recursion is where a function calls itself. Like most languages, we can define a recursive function. Many loops can be rewritten in a recursive way. In some functional languages, using recursion is the default way to loop through items.

However, they’re harder to understand, so to make reading the code easy, we stick with loops and array methods for iteration and manipulating data.

For instance, we the following loop:

for (let i = 0; i <= 4; i++) {
  console.log(i);
}

produces the same result as the following recursive function:

const loop = (i = 0) => {
  console.log(i);
  if (i === 4) {
    return;
  }
  loop(i + 1);
}

loop();

As we can see, the loop is much shorter and easier to understand.

With the recursive loop function, we have to run the console.log like we did with the for loop, but also have to check the base case which when i is 4, and then we have to end the loop if i reaches 4.

Otherwise, we let the function call itself.

It’s more useful for traversing tree structures with indefinite depth levels.

Conclusion

In JavaScript, functions are treated like any other object. We can set properties to it, pass it in as an argument, and functions can return functions.

Recursion is also an important part of functional programming. We can use it to create a function that calls itself.

Categories
Functional Javascript

More Javascript Functional Programming Features

JavaScript is an easy to learn programming language. It also uses lots of functional programming features that make our lives easier.

In this article, we’ll look at some functional programming features of JavaScript, including functors and pure functions.

Functor

A functor is something that can be mapped over. If an entity’s entries can be mapped to new values, then it’s a functor.

In JavaScript, anything that we can call the map method over is a functor. This would be an array in JavaScript.

For instance, with an array, we can call map as follows:

const arr = [1, 2, 3].map(a => a * 2);

In the code above, we passed in a callback that returns an array with each value of the original array doubled. Therefore, an array is a functor.

In addition to arrays, we can create arrays by converting array-like iterable objects into arrays with the spread operator.

For instance, if we have a generator function:

const generator = function*() {
  yield 1;
  yield 2;
  yield 3;
}

Then we can convert it to an array and call map on the converted array as follows:

const arr = [...generator()].map(a => a * 2);

In the code above, we used the spread operator to convert the iterator returned by generator into an array.

Then we get the same result as the first example.

Other examples of array-like iterable object include the arguments object, DOM NodeLists, sets, maps, and the Files object.

For non-iterable array-like objects. That is, objects that have numerical keys and the length property, we can use Array.from to convert it to an array.

We can call Array.from as follows:

const obj = {
  0: 1,
  1: 2,
  2: 3,
  length: 3
}
const arr = Array.from(obj).map(a => a * 2);

In the code above, we passed obj into Array.from to convert it to an array, then call map on it as we did in the previous examples.

Pure Functions

Pure functions are functions that always return the same output for a given set of inputs.

Also, they don’t produce any side effects. They’re useful because they’re easy to understand and test since they just manipulate inputs and return an output.

They also don’t commit any side effects so we don’t have things that happen outside the function itself that are caused by the function.

An example of a pure function includes:

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

The add function just takes 2 numbers and return the result added together, so it’s a pure function. It doesn’t modify anything outside the function, so it commits no side effects.

An example of a function that’s not pure is something like:

let foo = 1;
const impureAdd = (a, b) => {
  foo = 3;
  return a + b;
};

The impureAdd function commits a side effect by reassigning the foo variable, which is outside the function to a different value.

Therefore, impureAdd isn’t a pure function.

Side Effects

Side effects are any operation that’s observable outside the called function other than its returned value.

For instance, they include operations like:

  • changing values of variables outside a function
  • logging to the console
  • drawing on the screen
  • write file to disk
  • run external processes
  • calling other functions that commit side effects
  • … and anything else that does things outside the function

With functional programming, side effects are minimized so that a function is easier to read and test as we don’t have to check their side effect results.

Referential Transparency

Referential transparency is the fact that an expression may be replaced by its value or anything having the same value without changing the result of the program.

The function should always return the same value for a given argument without having any other effect.

Also, this means that our functions have no side effects.

For instance, the add function that we have above have referential transparency since we always get the same output for the same set of arguments passed in.

Conclusion

To make our code easy to read and test, we stick with pure functions as much as possible.

Side effects are avoided as possible so that we don’t have to deal with checking them.

Functors are anything that we can map their values over. In JavaScript, arrays have the map method, so JavaScript arrays are functors. We can also convert many kinds of objects to arrays, including iterable and non-iterable array-like objects.