Home > Net >  Why must functions have variables that equal to the sum of itself and an empty string
Why must functions have variables that equal to the sum of itself and an empty string

Time:09-09

In this code:


function reverse_a_number(n)
{
    n = n   "";
    return n.split("").reverse().join("");
}
console.log(Number(reverse_a_number(32243))); 

Its function is supposed to reverse any number.

Why must "n" be equal to ' n "" '?

In the return statement why must the split and join methods have an empty string and not reverse?

Why can't the code be like the one written below (I know it would read error, but I want understand why)?

function reverse_a_number(n)
{
return n.split().reverse().join();
}

console.log(Number(reverse_a_number(32243))); 

CodePudding user response:

Why must n be equal to n ""?

n = n   "";

is equivalent to

n = String(n);

This is needed because split() is a string method, it doesn't work with numbers.

In the return statement why must the split and join methods have an empty string and not reverse?

You have to give a separator to split(). Using an empty string means to turn each character into an element of the result array. If you omit the separator, the default is to put the entire string into a single array element.

For join(), the default separator is ,. So if you left this out you would get '3,4,2,2,3' instead of '34223'.

reverse() doesn't have any parameters. It simply reverses the array that it's called on, there are no options.

  • Related