Useful tricks in Javascript

Soktoev Aian
Aug 19 · 1 min read
  1. 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//

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store