Concepts of Javascript — Part 2

📄 Table of Contents

▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬ ✦ ✦ ✦ ▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬

◉ Functional Programming

In most simplest term, Functional Programming is a form of programming in which you can pass functions as parameters to other functions and also return them as values.

In functional programming, closures are frequently used for partial application & currying.

Concepts of functional programming:

  • Recursion
  • Immutability (Variables are Immutable)
  • Functions are First-Class and can be Higher-Order
  • Referential transparency

◉ First-Class Functions

In JavaScript functions are a special type of objects.They are Function objects. For example:

function greeting() {
console.log('Hello World');
}
// Invoking the function
greeting(); // prints 'Hello World'

To prove functions are objects in JavaScript, we could do something like this:

// We can add properties to functions like we do with objectsgreeting.lang = 'English';
console.log(greeting.lang); // Prints 'English'

Note => While this is perfectly valid in JavaScript, this is considered a harmful practice. You should not add random properties to the function objects, use an object if you have to.

In JavaScript, everything you can do with other types like object, string, or number, you can do with functions. You can pass them as parameters to other functions (callbacks), assign them to variables and pass them around etc. This is why functions in JavaScript are known as First-Class Functions.

◉ Higher-Order Functions

For example, Array.prototype.map, Array.prototype.filter and Array.prototype.reduce are some of the Higher-Order functions built into the language.

◉ Pure Functions

A pure function is independent of any state, or data change during a program’s execution. It must only depend on its input.

Pure functions are functions:-

  • Given the same input, will always return the same output.
  • Its output or return value must depend on the input/arguments.
  • pure functions must return a value.
  • Produces NO side effects, which means that it can’t alter any external state.

Examples:-

Math.max(2, 8, 5);        # 8const double = x => x * 2;Math.random();  # is NOT a pure function, WHY ? Even though we didn’t pass any arguments into any of the function calls, they all produced different output, meaning that `Math.random()` is not pure.

Let’s understand pure function with an example.

Below is a simple greeting function that takes the name of the person as input.

const greeting = "Hello";
const greet = person => `${greeting} ${person}!`;
console.log(greet("Ashmit")); // "Hello Ashmit!"

You may think that this will give the same output on the same input every time! Yes, that’s correct!

But it is not independent of whatever is happening outside the function. If we change the variable ‘greeting’ to “Howdy” the output will change even if we didn’t change the input to the ‘greet’ function.

const greeting = "Howdy";
const greet = person => `${greeting} ${person}!`;
console.log(greet("Ashmit")); // "Howdy Ashmit!"

A pure function should be independent of any external mutable state. It should only depend on its input. The above scenario is making our function impure because of its interaction with the outside mutable world, which is referred to as a Side Effect.

Let’s see in detail what the side effects actually mean with respect to pure functions.

Side Effect

Note: If a pure function calls a pure function this isn’t a side effect and the calling function is still pure.

Let’s make the impure ‘greet’ function pure, with a slight modification. We know that pure function should only be dependent on the inputs and should work the same even if the outside world is on fire. So we’ll do exactly that,

const greeting = "Hello";
const greet = (greeting, person) => `${greeting} ${person}!`;
console.log(greet(greeting, "Ashmit"));// "Hello Ashmit!"

Now our function ‘greet’ is pure as it only depends on its inputs. It will always give the same output with the same input.

Benefits of Pure functions

  • Pure functions are immediately testable once created and are also helpful in maintaining and refactoring code.

One very important and use-case of pure functions is in Redux ( State management for ReactJS ). The reducers must always be pure functions because reducers perform actions on the state. If reducers are impure for the same state of actions on the state of an application, it will yield different results and hence will fail its purpose!

Pure Functions have a huge performance impact during execution on the Browser. How ?

On the next call to the same function, with the same parameter, instead of executing the function again, the cached result is returned. Hence enhancing the Application Performance.

◉ Arrow functions vs Regular functions

  • Use of this keyword ❌
  • Availability of arguments objects ❌
  • Using new keyword ❌
  • arrow functions implicitly returns something, regular functions need to manually return something else it will return “undefined”
arguments & new NOT allowed in Arrow functions.

You cannot rebind this in an arrow function. It will always be defined as the context in which it was defined. If you require this to be meaningful you should use a normal function.

◉ Currying

Currying always returns another function with only one argument until all of the arguments have been applied. So, we just keep calling the returned function until we’ve exhausted all the arguments and the final value gets returned.

Note:

Curry takes a binary function and returns a unary function that returns a unary function.

A curried functions have a built-in iterator behaviour. One argument is applied at once which is then returned to the calling function to be used for next step.

🔹 Usages

  1. Ramda.js lib. functions are automatically curried and lodash has a function called curry which can be used to form curry function.
  2. Memoization is another good use case for curry function.
  3. Can create First class functions which means that we can use functions as arguments and return values.

🔘 Partial Application

JavaScript has the built-in method .bind that works on functions with any number of arguments and can bind an arbitrary amount of parameters. Its invocation has the following syntax.

.bind turns function into a new function.

🔘 Difference

  • Partial application produces functions of arbitrary number of arguments. The transformed function is different from the original — it needs less arguments.
  • Currying is not partial application. It can be implemented using partial application. You can’t curry a function that takes any number of arguments, (unless you fix the number of arguments).

Reference(s):

◉ Memoization

In the above example we are trying to square the number. So we have created an object square.cache where we will storing as key value pair. Line 2 we are checking in cache object for that particular key. If it is not present we will compute it and store it in square.cache object. If the key exists it won’t compute and what ever it is already stored in cache same it will return.

◉ Memory Leak in JS

[1]. Accidental global variable.

[2]. In case of Closures

[3]. Lingering DOM references to Removed Elements

It is important to note that, the local variable “outer of the outer function(parent) exists even after the outer function has returned, as the inner function child holds the reference to the outer function variable “outer, so the variable “outer” will not be garbage collected.

Whereas in regular functions, when the function returns, its local variables no longer exists.

In such case, we need to release the memory explicitly by assigning null to the variables.

result = null;

source: https://dev.to/somedood/emulating-private-variables-in-javascript-with-closures-and-factory-functions-2314

◉ Garbage Collector in JS

One way in which an object can be reached is if it’s assigned to a variable. Assigning a new value to a variable that presently points to an object (e.g. by assigning null to a) will reduce the reference count on that object by one. When this or any object's reference count is reduced to zero, it will qualify for garbage collection.

All that said, it’s not really important what value you use to replace the value of a variable, as long as it’s not some other object that would otherwise be garbage collected. For this reason, both undefined and null will work.

var info = {name: "anil", age: 25, status: "coder"};
info.name = undefined / null;
console.log(info);

For vs forEach() vs for/in vs for/of in for looping

There’s numerous ways to loop over arrays and objects in JavaScript, and the tradeoffs are a common cause of confusion.

The for and for/in looping constructs give you access to the index in the array, not the actual element. For example, suppose you want to print out the values stored in the below array:

const arr = ['a', 'b', 'c'];

With for and for/in, you need to print out arr[i]:

for (let i = 0; i < arr.length; ++i) {
console.log(arr[i]);
}
for (let i in arr) {
console.log(arr[i]);
}

With the other two constructs, forEach() and for/of, you get access to the array element itself. With forEach() you can access the array index i, with for/of you cannot.

const arr = ['a', 'b', 'c'];arr.forEach((key, index) => console.log(key));

for (const element of arr) {
console.log(element);
}
// expected output: "a"
// expected output: "b"
// expected output: "c"

Conclusions

The major downsides of for/of is that you need to do extra work to access the index , and you can't chain like you can with forEach(). forEach() comes with several caveats and should be used sparingly, but there are numerous cases where it makes code more concise.

(1) To access the current array index in a for/of loop, you can use the Array#entries() function.

for (const [i, v] of arr.entries()) {
console.log(i, v); // Prints "0 a", "1 b", "2 c"
}

Experience with Front-end Technologies and MERN / MEAN Stack. Working on all Major UI Frameworks like React, Angular.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store