כיצד ומדוע להשתמש בתכנות פונקציונאליות ב- JavaScript מודרני

במאמר זה תוכלו לקבל הבנה מעמיקה של תכנות פונקציונלי ויתרונותיו.

מבוא לתכנות פונקציונאלי

תכנות פונקציונלי (FP) הוא סוג של פרדיגמה או דפוס במדעי המחשב. הכל נעשה בעזרת פונקציות ב- FP ואבני הבניין הבסיסיות הן פונקציות בלבד.

שפות תכנות התומכות בתכנות פונקציונאלי בלבד:

  1. הסקל
  2. סגירת מעגל
  3. סקאלה
  4. SQL

חלק משפות התכנות התומכות בתכנות פונקציונאלי כמו גם בפרדיגמות תכנות אחרות הן -

  1. פִּיתוֹן
  2. Javascript
  3. C ++
  4. אוֹדֶם

מכיוון שהשם אומר פונקציונלי, רוב המתכנתים חושבים על פונקציות מתמטיות. זה לא המקרה עם FP. זוהי רק הפשטה לפתור בעיות מורכבות בעולם האמיתי בצורה קלה ויעילה.

לפני עידן התכנות מונחה האובייקטים, תעשיית התוכנה הייתה תלויה לחלוטין בתכנות פונקציונאלי. הפרדיגמה הזו טלטלה את תעשיית התוכנה במשך כמה עשורים. יש כמה בעיות בתכנות פונקציונלי ולכן עברו לפרדיגמה מונחה עצמים. הסוגיות עם FP יידונו בהמשך מאמר זה.

זה הכל על המבוא לתכנות פונקציונלי. עכשיו, קודם כל, עלינו ללמוד מהי פונקציה.

פונקציות

לפני שאחשוף את ההגדרה בפועל, אני רוצה להסביר מצב כדי לדעת היכן להשתמש בפועל ב- FP. נניח שאתה כותב קוד לבניית יישום. במסע הפיתוח שלך, אתה רוצה לעשות שימוש חוזר בקוד של כמה שורות (100) במקומות שונים. עבור היישום שלך, פונקציות מועילות. אנו יכולים לכתוב פונקציות במקום אחד ונוכל לגשת לפונקציות אלו מכל מקום בתוכנית. תכנות פונקציונלי כולל את התכונות הבאות -

  1. מפחית את יתירות הקוד.
  2. משפר את המודולריות.
  3. עוזר לנו לפתור בעיות מורכבות.
  4. מגביר את יכולת התחזוקה.

בואו נסתכל על ההגדרה בפועל של פונקציה:

פונקציה היא גוש קוד מוגדר המשמש לביצוע משימה ספציפית בתוכנית.

סוגי הפונקציות הפופולריים ביותר הם -

  1. פונקציות כלליות
  2. פונקציות חץ
  3. פונקציות אנונימיות

פונקציות כלליות

פונקציות כלליות אינן אלא הפונקציות שמשמשות לעתים קרובות למדי המתכנת לביצוע משימה ספציפית. התחביר להכריז על פונקציה כללית ב- Javascript הוא:

function functionName(parameters) { // code to be executed}

פונקציה - זוהי מילת מפתח הדרושה כדי להכריז על פונקציה.

functionName - ניתן למנות אותו על סמך עבודת הפונקציה.

פרמטרים - אנו יכולים להעביר כל מספר פרמטרים לפונקציה.

פונקציות מוצהרות אינן מבוצעות באופן מיידי. הם "נשמרים לשימוש מאוחר יותר", והם יבוצעו מאוחר יותר, כאשר הם מופעלים (נקראים).

עלינו להתקשר לפונקציה כאשר אנו רוצים לבצע את אותה פיסת קוד המוחזרת בתוך פונקציה.

הפונקציות הכלליות מסווגות כדלקמן -

פונקציות ללא ויכוח

איננו צריכים להעביר טיעונים לפונקציה.

// Function Declaration
function sayHello(){ alert('Hello...!');}
// Calling the functionsayHello()

כאשר אנו קוראים לפונקציה לומר Hello () היא תפיק את הודעת ההתראה כ- Hello.

פונקציות ויכוח

בסוג פונקציות זה נעביר להם טיעונים.

דוגמא

// Declaring a Function
function add(num1, num2){ return num1 + num2;}
// Function Call
var result = add(7, 11);
console.log(result);

הטיעונים המועברים תוך הכרזה על פונקציה כלומר (num1, num2) נקראים כפרמטרים רשמיים.

הטיעונים המועברים בזמן קריאה לפונקציה כלומר (7, 11) נקראים כפרמטרים בפועל.

פונקציה מחזירה בדרך כלל ערך כלשהו, ​​וכדי להחזיר ערך זה עלינו להשתמש במילת המפתח להחזיר . כאשר פונקציה מחזירה ערך כלשהו זה אומר שהיא לא מדפיסה שום פלט עבורנו, אלא רק מחזירה את הפלט הסופי. באחריותנו להדפיס את התוצאה. בתוכנית שלעיל, הפונקציה מחזירה את הערך ואני מעביר את הערך לשם המשתנה 'תוצאה'. כעת הפונקציה תעביר את התוצאה למשתנה 'התוצאה'.

המומחיות של פונקציות Javascript

אם תעביר יותר ארגומנטים מהמספר המוצהר, לא תקבל שום שגיאה. אבל בשפות תכנות אחרות כמו Python, C, C ++, Java וכו '... נקבל שגיאה. Javascript ישקול על פי הדרישות שלהם.

דוגמא

// Calling the function with more number of arguments than the declared number
var result1 = add(2, 4, 6);console.log(result1);
var result2 = add(2);console.log(result2);

תְפוּקָה

אם תעביר פחות טיעונים מהמספר המוצהר, אז גם לא נקבל שום שגיאה. אך איננו יכולים לחזות את תפוקת התוכנית מכיוון שעל פי פונקציונליות הפונקציה שלך הפלט יופק.

פונקציית טיעון משתנה

היתרון הגדול ביותר של פונקציות Javascript הוא שאנחנו יכולים להעביר מספר רב של ארגומנטים לפונקציה. תכונה זו מסייעת למפתחים לעבוד בצורה יעילה יותר בצורה עקבית.

דוגמא

// Creating a function to calculate sum of all argument numbers
function sumAll(){
let sum = 0;
for(let i=0;i
    
return sum;
}
// Calling the sumAll function
sumAll();
sumAll(1,2,3,12,134,3234,4233,12,3243);

Output

This is all about general functions that are used to perform our complex task in a simple manner. Now let’s discuss some advanced functions introduced in ES6 called Arrow Functions.

Arrow Functions

An arrow function expression is a syntactically compact alternative to a regular function expression. It doesn’t have its own bindings to the this, super, arguments or new.target keywords. Arrow function expressions are ill-suited as methods. They cannot be used as constructors.

One of the most loved features in Es6 are Arrow functions. This arrow function helps developers time and simplify function scope.

The syntax for the arrow function is:

const functionName = (parameters) => { // code to be executed}
 (OR)
var functionName = (parameters) => { // code to be executed}
 (OR)
let functionName = (parameters) => { // code to be executed}

Examples for Arrow Functions

Eg 1

Creating an Arrow function to say a welcome message to the users.

// Creating a Welcome function
let sayHello = () => { return 'Welcome to Javascript World...!';}
// Calling the function
console.log(sayHello())

Output

Eg 2

In this example, we are creating an Arrow function to generate the greatest of all numbers that are passed as an argument.

let maxNumber = (a,b,c,d) => {
 if(a > b && a > c && a > d) return a; else if(b > a && b > c && b>d) return b; else if(c > a && c > b && c > d) return c; else return d;}
// Calling the function
console.log(maxNumber(1,2,4,3));

Output:

Combination of Variable Arguments with Arrow Functions

Since we are working with an arrow function, it doesn’t support the arguments array by default like general function. It is our responsibility to declare explicitly that it supports the variable number of arguments

Eg 3

let varArgSum = (...args) => { let sum = 0;
 for(let i=0;i
     
return sum;
}
// Calling the Function
console.log(varArgSum());
console.log(varArgSum(1,2,3,4,5,6,7,8,9,10));

Output

This is how we can combine a variable number of arguments with arrow functions. Now let’s discuss Anonymous functions in JavaScript.

Anonymous Functions

An anonymous function is simply a function with no name. The purpose of using anonymous function is to perform a certain task and that task is no longer required to program. Generally, anonymous functions are declared dynamically at run time.

Anonymous functions are called only once in a program.

Example:

// Working with an Anonymous function
var a = 10; // Global Scope Variable.
// creating a function(function() {
 console.log("welcome to the world of Anonymous function");
 var b = 20; // b is a local scope variable.
 var c = a+b; // c is a local scope variable //a can be used because it is in the global scope
 console.log("Addition of two numbers value is: "+c);})();

Output

This is the concept of anonymous functions. I think I explained it in a simple and easy way.

Higher Order Functions

A higher-order function is a function that takes functions as an argument or that returns another function as a result.

The best example of higher-order functions in Javascript is that of Array.map(), Array.reduce(), Array.filter().

Example 1: Array.map()

// working with Array.map()
let myNumberArray = [4,9,16,25,36,49];
let mySquareRootArray = myNumberArray.map(Math.sqrt);
console.log(mySquareRootArray);

Output

Example 2: Array.reduce()

// working with Array.reduce()
let someRandomNumbers = [24,1,23,78,93,47,86];
function getSum(total, num){ return total + num;}
let newReducedResult = someRandomNumbers.reduce(getSum);
console.log(newReducedResult);

Output

Example 3: Array.filter()

// Working with array filter
let ages = [12,24,43,57,18,90,43,36,92,11,3,4,8,9,9,15,16,14];
function rightToVote(age){ return age >= 18;}
let votersArray = ages.filter(rightToVote);
console.log(votersArray);

Output

Recursion

This is one of the key topics in functional programming. The process in which a function calls directly or indirectly is called a recursive function. This concept of recursion is quite useful in solving algorithmic problems like the Towers of Hanoi, Pre-Order, Post-Order, In-Order, and some graph traversal problems.

Example

Let’s discuss a famous example: finding the factorial of a number using recursion. This can be done by calling the function directly from the program repeatedly. The logic for the program is

factorial(n) = factorial(n) * factorial(n - 1) * factorial(n - 2) * factorial(n - 3) * ….. * factorial(n - n);
// Finding the factorial of a number using Recursion
function factorial(num){ if(num == 0) return 1; else return num * factorial(num - 1);
}
// calling the function
console.log(factorial(3));
console.log(factorial(7));
console.log(factorial(0));

Output

Characteristics Of Functional Programming

The objective of any FP language is to mimic the use of mathematical concepts. However, the basic process of computation is different in functional programming. The major characteristics of functional programming are:

Data is immutable: The data which is present inside the functions are immutable. In Functional programming, we can easily create a new Data structure but we can’t modify the existing one.

Maintainability: Functional programming produces great maintainability for developers and programmers. We don’t need to worry about changes that are accidentally done outside the given function.

Modularity: This is one of the most important characteristics of functional programming. This helps us to break down a large project into simpler modules. These modules can be tested separately which helps you to reduce the time spent on unit testing and debugging.

Advantages Of Functional Programming

  1. It helps us to solve problems effectively in a simpler way.
  2. It improves modularity.
  3. It allows us to implement lambda calculus in our program to solve complex problems.
  4. Some programming languages support nested functions which improve maintainability of the code.
  5. It reduces complex problems into simple pieces.
  6. It improves the productivity of the developer.
  7. It helps us to debug the code quickly.

Disadvantages Of Functional Programming

  1. For beginners, it is difficult to understand. So it is not a beginner friendly paradigm approach for new programmers.
  2. Maintainance is difficult during the coding phase when the project size is large.
  3. Reusability in Functional programming is a tricky task for developers.

Conclusion

For some, it might be a completely new programming paradigm. I hope you will give it a chance in your programming journey. I think you’ll find your programs easier to read and debug.

This Functional programming concept might be tricky and tough for you. Even if you are a beginner, it will eventually become easier. Then you can enjoy the features of functional programming.

If you liked this article please share with your friends.

Hello busy people, I hope you had fun reading this post, and I hope you learned a lot here! This was my attempt to share what I’m learning.

I hope you saw something useful for you here. And see you next time!

Have fun! Keep learning new things and coding to solve problems.

Check out My Twitter, Github, and Facebook.