DEV Community

Cover image for Functions in JS before learning React
Rajshree Vatsa
Rajshree Vatsa

Posted on

Functions in JS before learning React

Hello Everyone πŸ‘‹
Thanks for all the ❀️ πŸ”– and πŸ¦„ on the previous post. I use this space to share beginner friendly stuff about front-end development.
Today, let's talk about functions concepts in JavaScript and React.


Functions

A short introduction to JavaScript functions.
In JavaScript, functions are actually objects. They have attributes and methods too. The only thing that differentiates them from objects is that they can be called.
syntax

function sum(a, b) {
  return a + b;            
}
Enter fullscreen mode Exit fullscreen mode

Ways to Declare Function in JavaScript

The most common ways are by using function declaration or by function operator.
Following are the different ways to declare a function :

  1. Function Declaration
    The most typical method, it allows hoisting i.e. can be used
    before declaration.

    function funcName(A1, A2...){}
    
  2. Function Expression
    It is most suitable to use when you want to assign your
    function as an object to a variable.

     var var_name = function funcName(A1,A2..){
     };
    
  3. Generator Function Declaration
    A function that uses yeild keyword to return a Generator-
    Iterator object on which next method can be called later.

     function* name(A1, A2..) {}
    

    Generator Function Expression

      function* function_name(A1,A2..){}
    
  4. Function Constructor
    The Function keyword is actually a constructor which creates
    a new function. This is the least preferred method.

       var var_name = new Function(A1,A2..,'FunctionBodyString');
    
  5. Arrow Function

    This function is used for its shorter syntax and to get rid of

    this value.

      var var_name = (A1, A2..) => {};
Enter fullscreen mode Exit fullscreen mode

Arrow Functions in React

Arrow Functions are a more concise way of writing functions, and are frequently used in React.

  • If there is only one statement inside function body then return and {} can be omitted. Also function keyword is not used.
  • In case of only one parameter, parameter parentheses is not used.
  • Use of Arrow functions prevent any errors caused by making use of this within callbacks.
 const arrowFunc = () =>
  'Hello';
 console.log(arrowFunc());
Enter fullscreen mode Exit fullscreen mode

Higher-Order Functions

A β€œhigher-order function” is a function that accepts functions as parameters and/or returns a function. A higher-order component (HOC) is an advanced technique in React for reusing component logic. HOC is easier to understand when knowing Higher-order functions beforehand.

Example

 import React from 'react';
  export const doIncrement = state =>
      ({ counter: state.counter + 1 });
Enter fullscreen mode Exit fullscreen mode
  • Map, filter, and reduce are some examples of HOFβ€Šβ€”β€Šand make transforming, searching, and summing easier!
.reduce()
  const Arr = [1, 2, 3, 4];

  const sum = Arr.reduce((last, current) 
  => {  
    return last + currentValue;
    });

  console.log(sum); //will print sum
Enter fullscreen mode Exit fullscreen mode
.filter()

   const Num = [1, 7, 2, 8, 9];
   const filterArr = Num.filter(n => {  
    return n > 5;
    });

Enter fullscreen mode Exit fullscreen mode
.map()
  const usernames = ['A', 'B', 'C', 'D'];
  const message  = usernames.map(member => {
  return member + ' hello.';
   })
Enter fullscreen mode Exit fullscreen mode

After learning about higher-order functions, all the fundamental knowledge is established to learn about React’s higher-order components.


Thanks for Reading

I hope it was helpful. See you on next post 😊.
github ⭐ linkedIn ⭐ Twitter

Discussion (2)

Collapse
lukeshiru profile image
LUKESHIRU

Nice post! 3 things worth mentioning:

  • You can write your arrow functions without {} and return:
numbers.reduce((total, number) => total + number);
numbers.filter(number => number > 5);
users.map(user => `Hello, ${user}!`);
Enter fullscreen mode Exit fullscreen mode
  • You can chain functions that return arrays:
users
  .filter(user => user.age > 21)
  .map(user => `${user.name} is an adult.`)
  .forEach(message => console.log);
Enter fullscreen mode Exit fullscreen mode
  • Higher-order functions is no a "React" thing, not even a JS thing, is a programming technique available in languages that have first class functions (functions that can be assigned as value, or passed as arguments). A HOF is just a function that takes a function as an argument or returns a function as a result. This can be done in a number of languages, so is not exclusive to React.

Cheers!

Collapse
jcubic profile image
Jakub T. Jankiewicz

It's worth using strings as arguments for Function constructor, so you know exactly how it works:

new Function('A1', 'A2', 'return A1 + A2');
Enter fullscreen mode Exit fullscreen mode