Functional JavaScript — Creating Functions

Image for post
Image for post
Photo by Obi Onyeador on Unsplash

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.

Pure Function Is a Mathematical Function

Pure functions are mathematical functions.

They exhibit all the same characteristics.

Given the same input, then return one output.

JavaScript and Functional Programming

JavaScript is partly a functional programming language.

It has some of the features, but it also allows us to program it in a non-functional way.

For instance, we can create a function in JavaScript that takes no arguments.

But functions are treated as first-class citizens.

So we can have higher-order functions.

JavaScript Functions

We can create a simple JavaScript function by writing:

We created an arrow function, which is available only in ES6.

We can assign it to a variable by writing:

Then we can call the function by writing:

Strict Mode

JavaScript has a strict mode to let us write better JavaScript code.

To enable strict mode, we can add the 'use strict' directive to add the make the code below it use strict mode.

For example, we can write:

to enable strict mode.

It’ll stop us from writing bad code like creating global variables accidentally:

Multiple Statement Functions

We can write functions with multiple statements.

For instance, we can write:

We have an assignment statement and a return statement to return the value.

Function Arguments

Functions can take arguments.

For example, we can write:

It takes a value and returns it.

ES5 functions are valid in ES6.

But it doesn’t work the other way around.

So we can’t use arrow functions in an ES5 only environment.

Functional Alternatives to Loops

We can rewrite loops in a functional way by abstracting out the loop body into its own function.

For example, instead of writing:

We can write:

Our forEach function has an array and fn parameters.

We loop through the array and call our function.

This way, we can abstract out our logic to the outside and pass it in.

If we use const , then we can’t assign a new value to forEach accidentally.

Image for post
Image for post
Photo by Dogancan Ozturan on Unsplash

Conclusion

We can create functions to a functional way by creating functions that don’t reference things from the outside.

Also, we can abstract out logic into their own functions and pass them in.

Written by

Web developer. Subscribe to my email list now at http://jauyeung.net/subscribe/. Email me at hohanga@gmail.com

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