Home > OS >  How to store a function into a variable in JS
How to store a function into a variable in JS

Time:11-09

I have the same function repeating over and over again. I'd like to combine it into one so that I can call it without having to write long code.

totalV
    .filter((nan) => nan)
    .reduce((a, b) => a   b, 0)
    .toFixed(2)

Basically, I want to save it into a const or something.. and then call it whenever needed I tried to do something like this:

const Vol =
    .filter((nan) => nan)
    .reduce((a, b) => a   b, 0)
    .toFixed(2)

But unfortunately I wasn't able to do so, because it's asking for "expression" or array to do this funciton on ( something before EXPRESSION.filter.reduce )

EDIT: MORE INFO

{
              totalV.filter((nan) => nan)
              .reduce((a, b) => a   b, 0)
              .toFixed(2) == 0.0
              ? 0
              : 
                  totalV.filter((nan) => nan)
                  .reduce((a, b) => a   b, 0)
                  .toFixed(2)}

So I have this conditional render that I'm writing in a few spots.. however totalV can change, but the rest of the code is the same.. so I thought to store the code that keeps repeating into a variable or something like

const repeatableCode = 
.filter((nan) => nan)
.reduce((a, b) => a   b, 0)
.toFixed(2)

but it refuses to work without an array/object being provided ahead of time

CodePudding user response:

Why just not

const complexArrayFunc = (array) => {
  if (!array) return []
  return array.filter((nan) => nan)
    .reduce((a, b) => a   b, 0)
    .toFixed(2)

CodePudding user response:

You can use lambdas (anonymous functions / arrow function expressions):

for example:

const repeatableCode = (totalV) => {
    return totalV
        .filter((nan) => nan)
        .reduce((a, b) => a   b, 0)
        .toFixed(2)
}

Learn more about it: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

  • Related