0
\$\begingroup\$

I was wondering what is the better way of writing? Having several variables to show the steps or rather do method chaining?

function count(string) {
    const array = string.split("");
    return array.filter(element => element === "a").length
}

function count(string) {
    return string
        .split("")
        .filter(element => element === "a")
        .length
}

Thank you in advance.

\$\endgroup\$
3
  • 1
    \$\begingroup\$ To prevent your question from being closed, please read and follow codereview.stackexchange.com/help/how-to-ask. \$\endgroup\$ Commented Jan 25, 2020 at 15:47
  • \$\begingroup\$ Method chaining Is really painful to debug. \$\endgroup\$
    – slepic
    Commented Jan 26, 2020 at 7:23
  • \$\begingroup\$ That's a terrible function name, count. What is it counting? Entries? Strings? Characters? From 1 to 10? \$\endgroup\$
    – Mast
    Commented Jan 26, 2020 at 8:57

3 Answers 3

4
\$\begingroup\$

In this case I would clearly go with the more concise version 2.

In general it can improve readability to assign complex expressions to variables with meaningful names and I would always prefer this to adding a comment. However, in this case there is neither the necessity to add a comment nor is the variable name array very meaningful. Just the opposite: You have to decode the second line by looking up array one line above if you want to understand what's going on.

Personally I would shorten the code some more:

function count(string) {
    return string.split("").filter(e => e === "a").length
}

In my opinion, the name element doesn't add much information here, so you might as well write e or x. When variable scope is very short, these short names are fine. When you read this code, you will never wonder where the hell this variable e is coming from and what it means. It literally refers to something defined on the same line.

\$\endgroup\$
2
\$\begingroup\$

Not everyone will agree, but I think the second option would most often be considered more readable and is probably the best option to use.

But it's worth noting that some devs might prefer the first option because they find it easier to console.log when something goes wrong.

\$\endgroup\$
2
\$\begingroup\$

I found the first one more readable and easy to understand. I know we shouldn’t declare a variable when we can return directly and I do the same usually but I think that return statement doing too many things in a single line.

\$\endgroup\$

Not the answer you're looking for? Browse other questions tagged or ask your own question.