JavaScript Tricks
Arrays are everywhere in Javascript, and we can do a lot of cool things with the spread operator, a new feature in ECMAScript 6. 1. Iterate over an empty array The array created directly in Javascript is loose, so that there will be many pitfalls. Try to create an array using the array constructor, and you’ll understand in no time. const arr = new Array(4); [undefined, undefined, undefined, undefined] // [empty x 4] in Google Chrome You will find it very difficult to loop through some transformations through a loose array. const arr = new Array(4); arr. map((elem, index) => index); [undefined, undefined, undefined, undefined] To fix this, you can use Array.apply when creating a new array. const arr = Array.apply(null, new Array(4)); arr. map((elem, index) => index); [0, 1, 2, 3] 2. Pass an empty parameter to the method If you want to call a method without filling in one of the parameters, Javascript will report an error. method('parameter1', , 'parameter3'); // Uncaught SyntaxError: Unexpected token ,A common solution is to pass null or undefined. method('parameter1', null, 'parameter3') // or method('parameter1', undefined, 'parameter3'); According to the introduction of the spread operator in ES6, there is a more concise way…