Like every other programming language, JavaScript has dozens of tricks to perform both easy and difficult tasks. Some tips are widely known while others are enough to blow your mind. Let’s take a look at some JavaScript tips that you can start using today!
1. Clearing or truncating an array
An easy way to delete or truncate an array without reassigning it is by changing the value of its length attribute:
1 2 | const arr = [11, 22, 33, 44, 55, 66]; |
1 2 | truncantingarr.length = 3; //=> [11, 22, 33] |
1 2 | // clearingarr.length = 0; //=> [] |
2. Object destructuring for array items
Assign array items to individual variables with object destructuring
1 2 3 | const str = '1997,John Doe,US, <a class="__cf_email__" href="/cdn-cgi/l/email-protection">[email protected]</a> ,New York'; const { 0: year, 2: country, 4: state } = str.split(','); |
1 2 3 | console.log(year) //=> "1997" console.log(country) //=> "US" |
3. Creating pure objects
You can create a 100% pure object, it does not inherit any properties or methods from the Object
1 2 | const pureObject = Object.create(null); |
1 2 3 4 5 | console.log(pureObject); //=> {} console.log(pureObject.constructor); //=> undefined console.log(pureObject.toString); //=> undefined console.log(pureObject.hasOwnProperty); //=> undefined |
4. Get Unique Values of an Array
Taking out an array with elements is unique, I have 1 article on Set vs Array
1 2 3 | const j = [...new Set([1, 2, 3, 3])] //=> [1, 2, 3] |
5. Array and Boolean
Do you ever need to filter falsy values (0, undefined, null, false, etc.) from an array? You may not know this trick:
1 2 3 4 5 6 7 | myArray .map(item => { // ... }) // Get rid of bad values .filter(Boolean); |
6. Converting to boolean using !! operator
Sometimes we need to check if some variables exist or if they have a valid value, to see if they are true. !! will help us to test this with an extremely concise syntax. For example
1 2 | const tmp = 123 |
1 2 3 | console.log(tmp) //=> 123 console.log(!!tm) //=> true |
7. Converting to number using + operator
1 2 3 | console.log(+"1234"); // 1234 console.log(+"ACB"); // NaN |
This + operator also works with Date
1 2 | console.log(+new Date()) // 1461288164385 |