How to transform a single element array into a number

Let's assume that we are working with the following function:

javascript
const countLetters = (...names) => {
    
    let totalLetters = names.map(name => name.length);
    
    return totalLetters;
    
}

let count = countLetters('Andrea', 'Jaruwan', 'Paula', 'Erik');

console.log(count);
// [6, 7, 5, 4]

The function counts the total letters for each name and returns an array with the results.

But what would happen if we only wanted to count one single name?

javascript
const countLetters = (...names) => {
    
    let totalLetters = names.map(name => name.length);
    
    return totalLetters;
    
}

let count = countLetters('Erik');

console.log(count);
// [4]

The function returns an array of one single element, which it may be undesirable.

To transform a single element array into a number, we could check its length:

javascript
const countLetters = (...names) => {
    
    let totalLetters = names.map(name => name.length);
    
    // Returns array if length > 1 or single value otherwise
    return totalLetters.length > 1 ? totalLetters : totalLetters[0];
    
}

let count_1 = countLetters('Erik');
let count_2 = countLetters('');
let count_3 = countLetters('Erik', 'Andrea');

console.log(count_1, count_2, count_3);
// 4, 0, [4, 6]

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.