JavaScript Quick Tips #1

Solutions to Common JavaScript Problems

#Problem

Alerting an object returns [object Object].

#Solution

Use JSON.stringify on the object before alerting.

Convert Object to JSON for Alert
1
2
var myVar = {myKey: 'myValue'};
alert(JSON.stringify(myVar));

#Problem

You want to use splice, but it is destructive.

#Solution

Use slice on the original array to make a copy. The spliced array will not affect the array created by slice.

Slice Before You Splice
1
2
3
4
5
6
7
8
9
10
var myArray = [1, 2, 3, 4, 5],
copyArray = myArray.slice();

myArray.splice(2,1);

//copyArray is your original
console.log(copyArray);

//myArray will be spliced
console.log(myArray);