DEV Community

Orkhan Jafarov
Orkhan Jafarov

Posted on • Updated on

🧙‍♂️ 9 JavaScript Tips & Tricks To Code Like A Wizard

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;
[ 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);
Enter fullscreen mode Exit fullscreen mode

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(;
// ["World", "JS", "Tricks"]
Enter fullscreen mode Exit fullscreen mode

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
// 474

const numbers = [100, 100, -1000, 2000, -3000, 40000];
// -3000
Enter fullscreen mode Exit fullscreen mode

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]]]];
// [ 10, 50, 100, 2000, 3000, 40000 ]
Enter fullscreen mode Exit fullscreen mode

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 => === 'Jim');
// TypeError: Cannot read property 'name' of undefined
Enter fullscreen mode Exit fullscreen mode

You can avoid it like this

const found = [{ name: "Alex" }].find(i => === 'Jim') || {};
// undefined
Enter fullscreen mode Exit fullscreen mode

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) =>
    .map((s, i) => `${i + 1}. ${s}`)

Hello, World
Hello, World
// 1. Hello
// 2. World
Enter fullscreen mode Exit fullscreen mode

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' }
Enter fullscreen mode Exit fullscreen mode

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' ]
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode


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)

tiagojpdias profile image
Tiago Dias

One that I often:

const collection = [obj1, obj2, undefined, obj3, undefined];
const cleanCollection = collection.filter(Boolean);
// [obj1, obj2, obj3]
Enter fullscreen mode Exit fullscreen mode

At first it may look odd but we just avoid one extra anonymous function and provide the .filter() argument into the Boolean() 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...

const collection = [obj1, obj2, {}, obj3, undefined];
const cleanCollection = collection.filter(Boolean);
// [obj1, obj2, {}, obj3]
Enter fullscreen mode Exit fullscreen mode
orkhanjafarovr profile image
Orkhan Jafarov • Edited

Yep! That's nice one to work with array of primitives.
I had this small helper that export from helper file.

export const clearArray = value => {
  const types = {
    string: v => !!v,
    object: v => v && (
        Array.isArray(v) ? v : Object.keys(v)
    number: v => !Number.isNaN(v),
  return types?.[typeof value]?.(value) ?? value;

and then import it and I put it as argument in the filter method.

import { clearArray } from './helpers';

const collection = [[], {}, "", null, undefined, NaN, "wee"];
const cleanCollection = collection.filter(clearArray);
//  ["wee"]
myogeshchavan97 profile image
Yogesh Chavan

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.

sakar_dhana profile image

Really nice tips and tricks. Thank you, keep the good work going...
Good health and happy living...

ansmtz profile image

Pt 6 is really surprising :)

qq449245884 profile image

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.

orkhanjafarovr profile image
Orkhan Jafarov

Hi, of course! Just put a link in comment I’ll share it too 👍