5 neat JavaScript tips
Tags: javascript, webdev, tutorial
Published: 2021-03-21 14:37:39

In this post, I'll show you 5 neat JavaScript tips that will help you become a better developer. Although this post requires some knowledge of JavaScript, I encourage everyone to read through it.

List of neat tips:
1. [Destructuring](#chapter-1)
2. [Console tips](#chapter-2)
3. [Dynamic key names](#chapter-3)
4. [Set as a data structure](#chapter-4)
5. [Callback-based APIs -> Promises](#chapter-5)

___

### Destructuring <a name="chapter-1"></a>

What a better way to explain something than through an example. Let's imagine we have an object with some tiger data and we need a function that will tell if the tiger is endangered.

```javascript 
const tiger = {
  specific: 'Bengal',
  latin: 'Panthera tigris tigris',
  endangered: true,
  weight: 325,
  diet: 'fox',
  legs: 4
}

// Bad code 💩
function isEndangered(tiger){
  if (tiger.endangered) {
    return `${tiger.specific} tiger (${tiger.latin}) is endangered!`
  } else {
    return `${tiger.specific} tiger (${tiger.latin}) is not 
      endangered.`
  }  
}

// Good code 👍
function isEndangered({endangered, specific, latin}){
  if (endangered) {
    return `${specific} tiger (${latin}) is endangered!`;
  } else {
    return `${specific} tiger (${latin}) is not 
      endangered.`;
  }  
}
// or 
function isEndangered(tiger) {
  const {endangered, specific, latin} = tiger;
  // the rest is the same
```
___
### Console tips <a name="chapter-2"></a>

#### Code execution time ⏲️

Use `console.time` and `console.timeEnd` to determine how fast (or slow) your code is?

Here's an example:
```javascript
console.time('TEST')

//some random code to be tested

console.timeEnd('TEST')
```

#### Loggin with style 😎

To have a custom output, we'll add `%c` like below and then have the actual *CSS* as the second argument.

```javascript
console.log('%c AWESOME', 'color: indigo; font-size:100px')
```

#### Tables

When you want to log an array of objects `console.table` will come in handy. 

```javascript
// x,y,z are objects
console.table([x, y, z])
```
#### Stack trace logs

If you want to get the stack trace of where a function is being called you can use `console.trace`

```javascript
function foo(){
  function bar(){
    console.trace('test')
  }
  bar();
}

foo();
```
___
### Dynamic key names <a name="chapter-3"></a>

A super useful tip!

```javascript 
const key = 'dynamic'

const obj = {
  dynamic: 'hey',
  [key]: 'howdy'
}

obj.dynamic // hey
obj[key] // howdy
obj['dynamic'] //hey
obj.key // howdy
```
[To see the most often use case of the dynamic-keys concept, check out my previous post.](https://blog.daliborbelic.com/posts/how-to-send-emails-from-a-form-in-react-emailjs-27d1/)
___

### Set as a data structure <a name="chapter-4"></a>

If I'd ask you to remove the duplicates from an array of numbers. How would you do it?

Use Set as a data structure to improve the functionality and performance of your app. Here's an example where I'll remove duplicates from an array of numbers using Set object.

```javascript
const arr = [1, 2, 2, 3]
const newArr = new Set(arr)
const unique = [...newArr]

// unique - [1, 2, 3]
```
___

### Callback-based APIs -> Promises <a name="chapter-5"></a>

To make things cleaner and more efficient you can transform the callback (ourCallbackFn) into a promise being a function.

```javascript
// we start with this 
async function foo() {
  const x = await something1()
  const y = await something2()
  
  ourCallbackFn(){
    // ...
  }
}

// the transformation
async function foo() {
  const x = await something1()
  const y = await something2()
  
  await promiseCallbackFn() //👀
}

function promiseCallbackFn() {
  return new Promise((resolve, reject) => {
    ourCallbackFn((err, data) => { //👀
      if (err) {
        reject(err)
      } else {
        resolve(data)
      }
    })
  })
}
```
___

This was a list of 5 JavaScript tips. Pretty neat, right? 
I hope you find my first post useful! Any feedback is greatly appreciated!

Thank You!

Dalibor