1. Usage of Unicode Character

“I hear and I forget. I see and I remember. I do and I understand.”

1
2
var rate = 3
"★★★★★☆☆☆☆☆".slice(5 - rate, 10 - rate);

2. An efficient way to handle JavaScript exception

1
2
3
4
5
6
7
8
// by 'Jordan Hall'
try {
//something
} catch (e) {
window.location.href =
"http://stackoverflow.com/search?q=[js]+" +
e.message;
}

3. Locate all DOM elements visually

1
2
3
4
5
6
7
8
// by 'Addy Osmani' https://addyosmani.com/
[].forEach.call($$("*"),function(a){
a.style.outline="1px solid #"+(~~(Math.random()*(1<<24))).toString(16)
})
Array.prototype.forEach.call(document.querySelectorAll('*'),
dom => dom.style.outline = `1px solid #${parseInt(Math.random() *
Math.pow(2,24)).toString(16)}`)

4. Separate number with ,

1
2
3
4
var test1 = '1234567890'
var format = test1.replace(/\B(?=(\d{3})+(?!\d))/g, ',')
console.log(format) //Output: 1,234,567,890

5. An unofficial way to do deep clone for JSON object

1
2
3
4
5
var a = {
a: 1,
b: { c: 1, d: 2 }
}
var b=JSON.parse(JSON.stringify(a))

6. Implicitly convert string to number

1
2
var a =1
+a

7. Usage of ES6 Spread Operator

1
2
3
4
5
// quickly remove duplicated number
[...new Set([2, "2", 3, 3, 4, 1])] //output: [2, "2", 3, 4, 1]
// create an array with length 3 and all number 2
Array(3).fill(2) //outpput: [2, 2, 2]

8. Find Max and Min use Math

1
2
3
var numbers = [-99, 0 , 99 , 98 , -1];
var maxNum = Math.max.apply(Math, numbers); // output: 99
var minNum = Math.min.apply(Math, numbers); // ouput: -99

9. Debugging tips

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// eye candy for JSON view
var fruits = [
{ fruit: 'Tangerine', weight: 43 },
{ fruit: 'Cherry', weight: 13 },
{ fruit: 'Litchi', weight: 25 }
];
console.table(fruits);
// output code snippets execution time period
console.time('Timer01');
var items = [];
for(var i = 0; i < 100000; i++){
items.push({index: i});
}
console.timeEnd('Timer01');

10. Remove Timers from Global Scope

1
2
3
4
var highestTimeoutId = setTimeout(";");
for(var i=0; i<hightestTimeoutId; i++){
clearTimeout(i);
}