Learning to be careful!

When programming you sometimes need to watch out a bit.
Suppose that (in javascript) you have the following:

var a = [ 4, 5, 6 ];

Now, say you want, for whatever reason, to create a copy of that array and perform operations on the copy. For example, you have a deck of cards and are dealing cards to players, and want to both remember the initial deck, and have a copy of the deck where you’ve removed the cards you’ve dealt.

The obvious thought might be to do this:

var b = a;

//Remove second element:

console.log (b, a);

Although the value of b might be obvious ([4, 6]), you will notice that a is also now [4, 6]. So obviously, this isn’t the way to go.
Instead, do this:

var b = a.slice();
//.slice copies a part of the array, with no parameters it will produce a copy of the whole thing.
//this is the right way to copy arrays!

//Remove second element:

console.log (b, a);

Although this may be obvious to some, it’s something that can slip your sight easily, and it had me break my code, so I thought it would be good to post about 🙂
Pay attention while coding, for things might not always do what you expect.

    Leave a Reply

    Your email address will not be published. Required fields are marked *

    This site uses Akismet to reduce spam. Learn how your comment data is processed.