More About JavaScript Functions - Types, HOF And Functional Programming

More About JavaScript Functions - Types, HOF And Functional Programming

ยท

5 min read

Functions in JavaScript are a very fundamental concept that we don't look at in very detail once we understand its basics. We will be looking at various types of functions that Modern ES6+ JavaScript allows us to write! Also, we will understand what Higher-Order functions are and what is Functional programming.

Back to basics - What are functions?

Functions are Blocks of code that have some code logic written inside of them. When you invoke a function inside a script, this block of code will be executed immediately in the runtime! The characteristic that differentiates normal lines of code and code written inside a Function is that the Function can be called within that script as many times as the developer wants. This is great as it helps JavaScript developers to write efficient and reusable code in their applications. Functions are awesome for writing readable code and following the DRY principle!

An example of code not written using Functions

const name = "Samir";
const profession = "Programmer";
console.log(`${name} is a ${profession}!`);

An example of code written using Functions

function getBio(name, profession) {
    console.log(`${name} is a ${profession}!`);
};
getBio("Samir", "Programmer");
getBio("Ravi", "Teacher")

Types of Functions

There are multiple ways to invoke or call a function in a JavaScript file. These are:

  1. Pure functions

  2. Anonymous functions

  3. Arrow functions

  4. Higher order functions

Pure Functions

Basic function declarations are called pure functions! All you have to do is write a function myFunctionName() {} declare a pure function. Write the code inside the curly braces that will be executed by the function.

Note! While writing functions we typically follow the camelCase naming convention!

Anonymous Functions

Do you know, you can even declare functions like you are declaring some normal variable? Functions created this way are called Anonymous functions because they are not initialized with a unique name or identifier.

const getRandomNumber = function () {
    return Math.random() * 1000;
}
getRandomNumber();

Here, the function does not have a name. It is an anonymous function that is stored inside the getRandomNumber variable. You will use this variable name only to call the function.

It may look like the function does have a name here. But the reality is that the function is anonymous which is associated with the variable. I personally also like to call them nameless functions!

Arrow Functions

Arrow functions were introduced in the ES6 JavaScript release! They are yet another intuitive way to write function methods inside a JavaScript file. Here is how.

As the name implies, you declare an arrow function using this syntax () => {} A pair of parenthesis followed by an equal and greater sign (to denote an arrow) and finally the curly brackets.

Curly brackets can be omitted if you writing a One-liner function, which makes Arrow functions an ideal choice to write small utility functions.

These functions are also anonymous by nature and can be associated with a variable declaration to call it later.

const pluralize = (word, n) => n > 1 ? word + 's' : word

console.log(pluralize('apple', 6))
// 'apples'
console.log(pluralize('apple', 0))
// 'apple'

There is one more situation where Arrow & Anonymous functions can be used, which we will discuss in the next section.

Higher order functions

This one is important! Higher-order functions are Functions that take another function as a callback.

Yes! Passing a function as a callback inside another function, so that the argument function can be called later. This is possible in JavaScript with the help of Higher-order functions, and in my opinion, it is one of the most powerful features for us JavaScript developers.

We can pass a function that will execute some code upon finishing the main function. For example, we may pass a predicate function inside a main function that will call the predicate on each iteration and determine if the iteration meets the predicates' conditions and then return the Boolean value accordingly.

In the following example we are taking a look at Array.map() function which is a higher-order function

const fruits = ["Mango", "Apple", "Banana"];
fruits.map((fruit) => console.log(`I ate one ${fruit}!`))

The map() method function of the Array calls the passed arrow function on each element of the array. The arrow function then takes the fruit and logs it to the console inside a string sentence.

This is also one of the ways you can use Arrow or Anonymous functions! You can still declare a pure function and pass that to the parameter of the map() instead. But using an anonymous function makes the code more readable and efficient to write!

Tip! Passing a pure function as a parameter might be a better choice when you are doing a lot of complex logic inside that function.

Functional Programming in JavaScript - a new perspective

Functional programming is a paradigm of programming in JavaScript in which you write and make use of Functions to write your application code. This paradigm strongly encourages that you only use functions to write your logic in more smaller and reusable function components, so that you can avoid the risks of unexpected data changes and side effects. A paradigm means a set of rules and conventions that you follow.

Functional programming helps you write code that is more readable and maintainable. You abstract away all the necessary parts of logic inside a function so that you can use it later effectively.

Additionally, each function is assigned its scope. This means that code written inside these functions will not affect anything outside of the function code. It is completely isolated, so you can be assured that it will not cause any unexpected data changes or side effects.

If the data changes unexpectedly during runtime, you would be spending so much time debugging the code figuring out what is the real issue here! This is why when writing functional code you are making sure that you don't mutate any variables or datatypes that should not change in runtime (and for that reason, you must also use const over let and var)

The End!

That is all you need to know about JavaScript functions and functional programming. Make sure you are fully utilizing the benefits of these types of functions to write better code in your project!

If you have made it to the end of this article, Thank you so much for reading this! ๐Ÿ’

ย