By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,442 Members | 1,373 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,442 IT Pros & Developers. It's quick & easy.

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

P: 30
I'm creating a couple helper methods to beef up the Array type: Array.shuffle() and Array.rotate(steps) (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.
Dec 22 '08 #1
Share this Question
Share on Google+
3 Replies

rnd me
Expert 100+
P: 427
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.
Dec 22 '08 #2

P: 30
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.
Dec 22 '08 #3

rnd me
Expert 100+
P: 427
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.
Dec 22 '08 #4

Post your reply

Sign in to post your reply or Sign up for a free account.