JS Array Methods, Best Practice: When to modify, when to return a copy?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • FLEB
    New Member
    • Aug 2008
    • 30

    #1

    JS Array Methods, Best Practice: When to modify, when to return a copy?

    I'm creating a couple helper methods to beef up the Array type: Array.shuffle() and Array.rotate(st eps) (rotates an array like [1,2,3,4,5], [2,3,4,5,1], [3,4,5,1,2], etc). What I'm wondering is what the consensus is on modifying the original array, versus returning a new array.

    My instinct is that in these cases, since they're operations on the array itself, I should simply modify the array in-place.
  • rnd me
    Recognized Expert Contributor
    • Jun 2007
    • 427

    #2
    array prototypes don't modify the orig (unless you hard code a variable name into the method), so i would say that returning a copy is the normal practice.

    Comment

    • FLEB
      New Member
      • Aug 2008
      • 30

      #3
      You know what... I actually just found this out. Apparently assigning a value to "this" is not allowed, so I have to use copies. It's a bit odd, though, since a few of the String object builtins operate directly on the object (such as "sort" and "splice"). I'm not sure how you'd implement this in pure JS-- some sort of iteration?

      Edit: Playing with it further...

      Although it does seem to work if I use a simple assignment (by reference, as JS does with objects) of "this" to a different var name.

      Edit again: Nope. Scratch that. Assigning "that = this" just makes a copy.

      Comment

      • rnd me
        Recognized Expert Contributor
        • Jun 2007
        • 427

        #4
        neither "sort" or "splice" is a string method.
        i think all native string protos return a copy.

        some native array methods do affect the original; examples include pop and push.

        custom ones do not, although you can return something besides "this"...

        you can clobber the array by referring to it's variable name in a proto, but that makes it pretty fragile.

        Comment

        Working...