Home > javascript > concatenate()

concatenate()

January 26th, 2008

Updated 2008.01.28: Great idea from Marc and Hendrik. Very slick.

function concatenate(){
  // return arguments.join('');                      // won't work. arguments is not a real array.
  // return [].splice.call(arguments,0).join('');    // old 'n busted
     return Array.prototype.join.call(arguments,''); // new hotness
}
 
concatenate('good',2,'go');
// ==> 'good2go'

Paul Irish javascript

  1. January 28th, 2008 at 08:08 #1

    function concatenate() {
    return Array.prototype.join.call(arguments, ");
    }

  2. January 28th, 2008 at 10:20 #2

    @Marc, while I do like how yours is cleaner from a syntax POV, I'm of the camp who say extending native objects is verboten.

    {Editor's note May 2010: Haha. 2.5 years ago I was scared shitless of any code that had the keyword prototype. Whoops. Shows my ignorable, for sure. :) ]

  3. Hendrik
    January 28th, 2008 at 13:56 #3

    Uh, Marc isn't extending anything. He's just calling the built-in join() function and setting its 'this' to the 'arguments' object.

    The 'arguments' object has a length and can be accessed with [index], and that's enough for join() to run.

    Ecma-262 specifically tells you they've been anticipating that:

    "The join function is intentionally generic; it does not require that its this value be an Array object.
    Therefore, it can be transferred to other kinds of objects for use as a method."

  4. January 28th, 2008 at 15:07 #4

    Ah, that's totally cool!
    If join() did require its input be arrays then we'd go with the [].splice method, but this is much nicer.

    Hmm that makes me think:
    What other functions get used like this? (Hijacking their methods for use with other objects?)

  5. January 29th, 2008 at 09:03 #5

    That new hotness method is really nice! And of course it brings a warm fuzzy feeling knowing that the join function was even intended to be used like that.

    Ok, these Javascript notes of yours mr. Irish hereby require me to add you to my RSS reader ;)

For code blocks, use <pre lang="javascript">. css and html4strict are also accepted.

i left this space here for you to play. <3