1. Generate numbers between a range
There are some situations when we create an array with numbers range. Let's say for birthday input where you need that range. Here's the easiest way to implement it.
let start = 1900,
end = 2000;
[...new Array(end + 1).keys()].slice(start);
// [ 1900, 1901, ..., 2000]
// also this, but more unstable results for big range
Array.from({ length: end - start + 1 }, (_, i) => start + i);
2. Use array of values as arguments for functions
We have cases when you need to collect your values in array(s) and then pass it as arguments for function. With ES6 you can just use spread operator (...) and extract your array from [arg1, arg2] > (arg1, arg2)
const parts = {
first: [0, 2],
second: [1, 3],
};
["Hello", "World", "JS", "Tricks"].slice(...parts.second);
// ["World", "JS", "Tricks"]
You can use it with any function
3. Use values as arguments with Math methods
So, we're good in spreading values to put them into functions. When we need to find Math.max or Math.min of our numbers in array we do it like below.
// Find the highest element's y position is 474px
const elementsHeight = [...document.body.children].map(
el => el.getBoundingClientRect().y
);
Math.max(...elementsHeight);
// 474
const numbers = [100, 100, -1000, 2000, -3000, 40000];
Math.min(...numbers);
// -3000
4. Merge/flatten your arrays in arrays
There's a nice method for Array called Array.flat
, as an argument it needs depth you need to flat (default: 1)
. But what if you don't know the depth, you need to flatten it all. We just put Infinity
as the argument. Also there's a nice flatMap method.
const arrays = [[10], 50, [100, [2000, 3000, [40000]]]];
arrays.flat(Infinity);
// [ 10, 50, 100, 2000, 3000, 40000 ]
5. Preventing your code crash
It's not good to have unpredictable behavior in your code, but if you have it you need to handle it.
For example. Common mistake TypeError
, if you're trying to get property of undefined/null and etc.
Note. Use it if your project doesn't support optional chaining
const found = [{ name: "Alex" }].find(i => i.name === 'Jim');
console.log(found.name);
// TypeError: Cannot read property 'name' of undefined
You can avoid it like this
const found = [{ name: "Alex" }].find(i => i.name === 'Jim') || {};
console.log(found.name);
// undefined
Of course it depends on situations, but for minor handle it's okay. You don't need to write huge code to handle it.
6. Nice way to pass arguments
Good example of using this feature is styled-components
, in ES6 you can pass Template literals as argument for function without brackets. Nice trick if you're implementing function that format/convert your text.
const makeList = (raw) =>
raw
.join()
.trim()
.split("\n")
.map((s, i) => `${i + 1}. ${s}`)
.join("\n");
makeList`
Hello, World
Hello, World
`;
// 1. Hello
// 2. World
7. Swap variables like a wizard
With Destructuring assignment syntax we can easily swap variables.
let a = "hello";
let b = "world";
// Wrong
a = b
b = a
// { a: 'world', b: 'world' }
// Correct
[a, b] = [b, a];
// { a: 'world', b: 'hello' }
Solution for wrong way is to add third temporary variable :(
8. Sort by alphabetical order
I worked a lot in international companies and their apps had non-english data. When you do your "awesome" tricks to sort list of this kind of data it looks okay, sometimes because there're just a few strings for that moment. Maybe it looks okay cause you don't know that language's alphabet.
Use correct one to be sure that it's sorted by alphabetical order for that language.
For example. Deutsche alphabet
// Wrong
["a", "z", "Γ€"].sort((a, b) => a - b);
// ['a', 'z', 'Γ€']
// Correct
["a", "z", "Γ€"].sort((a, b) => a.localeCompare(b));
// [ 'a', 'Γ€', 'z' ]
9. Mask it nicely
Final trick is about masking strings. When you need to mask any variable. Not password of course :) it's just example. We just get part of string substr(-3)
, 3 characters from its end and fill length that left with any symbols (example *
)
const password = "hackme";
password.substr(-3).padStart(password.length, "*");
// ***kme
// Hmmm I guess your first attempts might be wrong
Conclusion
Try to have nice and clean code. Save all tricks you would like to use in your code and track change logs of JavaScript.
Have a great dev-day! π
Save and contribute tips/tricks on github code-like
Top comments (7)
One that I often:
At first it may look odd but we just avoid one extra anonymous function and provide the
.filter()
argument into theBoolean()
function directly. Short and clean.Boolean()
will return true for truthy values and false for falsy values (null
,undefined
,0
,''
,false
).It's a nice way to clean up arrays. Use it wisely.
PS:
[]
and{}
are not falsy values as you may think at first...Yep! That's nice one to work with array of primitives.
I had this small helper that export from helper file.
and then import it and I put it as argument in the filter method.
You're right. using
Boolean
directly makes code shorter and is really helpful. Some days back I had written an article describing the same with truthy and falsy values.Really nice tips and tricks. Thank you, keep the good work going...
Good health and happy living...
Thanks!
Pt 6 is really surprising :)
Hello, may I translate your article into Chinese?I would like to share it with more developers in China. I will give the original author and original source.
Hi, of course! Just put a link in comment Iβll share it too π