Useful tricks in Javascript
1 min readAug 19, 2020
- Clearing or truncating an array
An easy way of clearing or truncating an array without reassigning it is by changing its length
property value:
const arr = [1, 2, 3, 4, 5, 6];arr.length = 4; console.log(arr); //=> [1, 2, 3, 4]arr.length = 0; console.log(arr); //=> []
console.log(arr[3]); //=> undefined
2. Creating pure objects
You can create a pure object, which won’t inherit any property or method from Object (for example, constructor
, toString()
and so on).
const pureObject = Object.create(null);
console.log(pureObject); //=> {}console.log(pureObject.constructor); //=> undefined
console.log(pureObject.toString); //=> undefined console.log(pureObject.hasOwnProperty); //=> undefined
3. Removing duplicate items from an array
By using ES2015 Sets along with the Spread operator, you can easily remove duplicate items from an array:
const removeDuplicateItems = arr => […new Set(arr)];
removeDuplicateItems([228, 'abc', 228, 'abc', true, true]);
//=> [228, "abc", true]
4. Flattening multidimensional arrays
Flattening arrays is trivial with Spread operator:
const arr = [1, [2, 3], [4, 5], 6];
const flatArr = [].concat(…arr); //=> [1, 2, 3, 4, 5, 6]
5. Swap variables
Using Array Destructuring to swap variable’s values:
let a = 'world', b = 'hello'
[a, b] = [b, a]
console.log(a) // -> hello
console.log(b) // -> world//