A little question about variables naming

From the code below, is it clear enough, what am I doing and what is each variable representing?

//Work out the first ten digits of the sum of the following
//large nums
function largeSum(arr) {

    return Number(arr.map(
      textNum => textNum.substring(0, 11)
      ).reduce(
        (sum, textChunkofNum) => sum + Number(textChunkofNum), 0
        ).toString().slice(0, 10));
  }

What kinds of values does arr contain? What does it represent? What is an example call to the function? It is not clear by the function name exactly what is going to be summed. I would assume it is an array of numbers, but I the code reads as it is an array of strings.

I would break things down a bit more instead of doing it all in one return statement. If nothing else, I would indent the code differently to make it more readable:

function largeSum(arr) {
    return Number(
      arr
        .map(textNum => textNum.substring(0, 11))
        .reduce((sum, textChunkofNum) => sum + Number(textChunkofNum), 0)
        .toString()
        .slice(0, 10)
    );
  }
2 Likes

Got it. You propose use each line for every method.
I thought it would be readable enough, if two methods are placed in one line, if they don’t have much inside parenthesis

toString().slice(0, 10))

arr parameter could be easily renamed, I guess largeNums would be ok.

To add example of function call - also totally makes sense.

I didn’t change name of the function, in order to pass the tests in the challenge step.

When chaining more than two methods, then convention is one line (or more if the callback is long) per method.

1 Like

If my aim is to make the code more readable, beside clear naming, id also warp different parts of the code into variables and make the calculations before i give the result to return. For example you can take out the callbacks you pass to each method and use a name on what its prupose is.

// unsure of the purpose of this callback, so i called it mapper...
const mapper = textNum => textNum.substring(0, 11)
arr.map(mapper)

Also if you have reduce in the equation, usually you can include whats done in the map method directly in the reduce.

// again, dont get focused on my naming
const chunkify = textNum => textNum.substring(0, 11)
reduce((sum, textNum) => sum + Number(chunkify(textNum)), 0)
1 Like

Eh, I’m not wild about creating a bunch temporary variables. You increase the number of places that you need to change stuff in an update. Also, it leaves you bouncing around to understand the logical flow.

Chaining is good thing. Use good variable names inside of the chaining to make it clear what each step does.

In compiled languages, chaining can help the compiler optimize out intermediate data structures.