Logo
Unit 9 – Functional Programming in JS

Functional Programming in JS

Duration: 10 minutes

Greetings, virtuoso of the virtual world!

In the realm of programming, a paradigm has re-emerged from the depths of the computational annals, shedding new light on how we approach problem-solving:

Functional Programming (FP). As JavaScript developers, we are in a unique position to utilize the elegance of FP principles, thereby bringing greater clarity and predictability to our code.

Understanding Functional Programming in JS

Pure Functions: A function is deemed pure if its output is solely determined by its input, and it has no side effects.

function square(x) {
return x * x;
}

Immutability: In FP, once data is created, it cannot be changed. Instead of modifying data, we create a new copy.

const array = [1, 2, 3];
const newArray = [...array, 4]; // Original array remains unaltered

Higher-Order Functions: Functions that accept other functions as arguments or return functions.

function greet(fn) {
console.log(fn());
}
function sayHello() {
return 'Hello!';
}
greet(sayHello); // Outputs: Hello!

Map, Filter, and Reduce: Essential utilities in functional programming that operate on arrays.

const numbers = [1, 2, 3, 4];
const doubled = numbers.map(n => n * 2);

Exercise

Prepare yourself, intrepid coder, for a challenge of functional refinement:

  • Given an array of numbers, perform the following tasks in a functional manner:
  • Filter out even numbers.
  • Double the remaining odd numbers.
  • Sum the doubled odd numbers.

Hints for the exercise:

  • Use Array.prototype.filter to exclude even numbers.
  • Leverage Array.prototype.map to double the numbers.
  • Finally, employ Array.prototype.reduce to compute the sum.

To guide your quest, behold the code structure below:

const numbers = [1, 2, 3, 4, 5, 6];
const result = numbers
.filter(num => num % 2 !== 0)
.map(num => num * 2)
.reduce((acc, num) => acc + num, 0);
console.log(result); // This should output the sum of doubled odd numbers

Conclusion

Brilliantly executed! By embracing the principles of functional programming, you’ve illuminated your JavaScript journey with an elegant, predictable, and modular approach. As you further traverse the lands of code, may the purity of functions and the absence of side effects be your guiding lights. Onward, seeker of functional clarity!

Next Tutorial: Node.js Introduction

10 minutes Minutes

Continue

Code on the Go with our Mobile App!

Unleash your coding potential anytime, anywhere!

Download Now!