🧙‍♂️ 9 JavaScript Tips & Tricks To Code Like A Wizard
Tags: javascript, beginners, webdev, tutorial
Published: 2020-09-13 15:06:19

---
title: 🧙‍♂️ 9 JavaScript Tips & Tricks To Code Like A Wizard
published: true
description: Practical tips & tricks for javascript developers
tags: #javascript #beginners #webdev, #tutorial
//cover_image: https://direct_url_to_image.jpg
---

### 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.

```js
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)`

```js
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.

```js
// 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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap) method.

```js
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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining?fbclid=IwAR2_X1H9hAPhmChM5ACKNrYHMWb-vA0G7KOmakCmhURzjl5Biy4ta8_bQrM)

```js
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
```js
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.

```js
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.

```js
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
```js
// 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 `*`)

```js
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](https://github.com/gigantz/code-like)