Search code examples
javascriptargumentscallapply

Javascript: Arguments


Function 1

function myConcat (separator) {
    var args = Array.prototype.slice.call(arguments, 1);
    return args.join(separator);
}

var a = myConcat(", ", "red", "orange", "blue");

Function 2

function myConcat () {
    var args = Array.prototype.slice.call(arguments, 1);
    return args.join();
}

var a = myConcat(", ", "red", "orange", "blue");

Can someone tell me why there is a difference between these two?

Many Thanks


Solution

  • Question has changed, so does the answer.

    In 1 the function let's you decide which separator to use, passing it a s the first argument. You don't need to define the separator argument, but can be convenient for readability reasons, that is, a programmer looking at your function can understand immediately that the first argument is the separator used.

    The same result can be achieved without defining it though, just assuming the first parameter is the separator to be used:

       function myConcat () {
         // transform array like object in array 
         var args = Array.prototype.slice.call(arguments, 0);
         // remove first element and use it as separator
         var separator = args.shift();
         // join other arguments with separator
         return args.join(separator);
       }
    
       var a = myConcat(", ", "red", "orange", "blue");
    
       document.getElementById('result').innerHTML = a;
    <div id="result"></div>

    here the separator is taken using the shift function which removes and returns the first element of an array.

    And if you're wondering what the hell is doing the slice part, is simply transforming the arguments array-like object into a real array

    In 2 the separator is fixed, and is the default separator of the js join function, which is a comma. Also calling 2 passing a comma as first argument is a NON SENSE, and to write 2 with some sense, you should do something like that:

    function myConcat () {
      var args = Array.prototype.slice.call(arguments, 0);
      return args.join();
    }
    

    and then calling it this way: var a = myConcat("red", "orange", "blue");