🧙♂️ 9 JavaScript Tips & Tricks To Code Like A Wizard
Orkhan Jafarov
Posted on September 13, 2020
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
Posted on September 13, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
October 25, 2024
October 6, 2024