Node.js - Modern JavaScript
Tags: javascript
Published: 2020-12-04 17:23:44

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/pfqepbg2xsq93va2byhp.jpeg)

This article is **Part 3** of [Working With NodeJS](https://dev.to/meddy672/series/20844), a series of articles to help simplify learning Node.js. In this topic, I will cover some tips on modernizing your JavaScript code.

#### Introduction
So you were tasked to write some code in JavaScript, and you've completed the task. Now, you want to submit your code for review so it can be merge to the project repository. Here are some things you should consider to give your code a cleaner look.

### Variables



##### Unpacking Arrays
```javascript
const x = [1, 2, 3, 4, 5];

let [y, z] = x;
console.log(y); // 1
console.log(z); // 2
```
*Use Case* - `x[0]`, `x[1]`



##### Object Destructuring
```javascript
const user = { id: 1, firstName: 'John', lastName: 'Doe' };

const { firstName, lastName } = user;
console.log(firstName); // John
console.log(lastName); // Doe
```
*Use Case* - `user.firstName` and `user.lastName`



##### Conditional Initializing
```javascript
const fee = isMember ? '$2.00' : '$10.00';
```
*Use Case* - `if/else`



##### Copying Object Properties
```javascript
const obj1 = {
    name: 'John Doe',
    email: 'doe@email.com',
};

const obj2 = {
    id: 1,
    ...obj1
};
```
*Use Case* - `Object.assign({}, obj1);`


### Arrays

`forEach` to loop 
```javascript
const items = [
    { id: 1, name: "TV", price: 300 },
    { id: 2, name: "Stereo", price: 100 },
    { id: 3, name: "Computer", price: 1800 },
];

items.forEach((item) => { // do something... });
```
*Use Case* - I want to loop through each index in the array and do something to it.

`map` a new array
```javascript
const items = [
    { id: 1, name: "TV", price: 300 },
    { id: 2, name: "Stereo", price: 100 },
    { id: 3, name: "Computer", price: 1800 },
];

const halfOffItems = items.map((item) => { 
    return {
        ...item,
        price: item.price / 2
    }
 });
```
*Use Case* - I want a new array containing new copies or changes of each array element.

`filter` an array 
```javascript
const items = [
    { id: 1, name: "TV", price: 300 },
    { id: 2, name: "Stereo", price: 100 },
    { id: 3, name: "Computer", price: 1800 },
];

const expensiveItems = items.filter(item => item.price > 500);
```
*Use Case* - I want a new array containing just the items I need.

`reduce` an array
```javascript
const items = [
    { id: 1, name: "TV", price: 300 },
    { id: 2, name: "Stereo", price: 100 },
    { id: 3, name: "Computer", price: 1800 },
];

const itemTotal = items.map(item => item.price)
    .reduce((prev, next) => prev + next);
console.log(expensiveItems); // 2200
```
*Use Case* - I want to reduce my array to a single value.

`find` an element in array
```javascript

const items = [
    { id: 1, name: "TV", price: 300, promo: false },
    { id: 2, name: "Stereo", price: 100 , promo: false },
    { id: 3, name: "Computer", price: 1800, promo: true },
];

const promoItem = items.find(item => item.promo);
console.log(promoItem); // returns third object in items

```
*Use Case* - I want to find a particular element in my array.

`some` an array
```javascript

const items = [
    { id: 1, name: "TV", price: 300, promo: false },
    { id: 2, name: "Stereo", price: 100 , promo: false },
    { id: 3, name: "Computer", price: 1800, promo: true },
];

const hasPromo = items.some(item => item.promo);
console.log(hasPromo); // true
```
*Use Case* - I want to check if any value(s) in my array meet a certain condition.




### Functions

##### Closures - I want to call a function within a function. 
```javascript
function init(type) {
    let id = 0;
    return (name) => {
        id += 1;
        return { id: id, type: type, name: name };
    }
}
const createUser = init('user');
const createBook = init('book');
const dave = createUser('Dave');
const book = createBook('A book');
console.log(dave); //prints {id: 1, type: 'user', name: 'Dave'}
console.log(book) //prints {id: 1, type: 'book', name:'A book'}
```
The `createUser` and `createBook` have access to separate instances of the `init` functions closure scope.

##### Closure 2 - Another approach
```javascript
 function doFunc() {
     let id = 0;
    function doSomething() {
        console.log('Do something...');
    }
    function doWork(name, email) {
         id += 1;
        console.log('Do work on user', name);
    }
    return {
         doSomething: doSomething,
         doWork: doWork,
    };
}
const fn = doFunc();
fn.doSomething();
fn.doWork('Timmy', 'tim@email.com');
// Do something...
// Do work on user Timmy
```

##### Destructure Parameters
```javascript
function myFunc({ id, firstName, lastName }) {
    console.log(id); // 1
    console.log(firstName); // John
    console.log(lastName); // Doe
}
const user = { id: 1, firstName: 'John', lastName: 'Doe' };
myFunc(user);
```

### Classes
##### Classes and inheritance are available in JavaScript 
```javascript
class Person {
    constructor(name) {
      this.name = name;
    }
    greet() {
      console.log(`Hello ${this.name}!`);
    }
  }
  
class Student extends Person {
    constructor(name, level) {
      super(name);
      this.level = level;
    }
    greet() {
      console.log(`Hello ${this.name} from ${this.level}`);
    }
  }
  
  const max = new Person("Max");
  const tina = new Student("Tina", "1st Grade");
  const mary = new Student("Mary", "2nd Grade");
  
  max.greet();
  tina.greet();
  mary.greet();
```

The purpose of this article was to demonstrate some modern JavaScript code. If you found this article helpful please leave a rating and subscribe to the series.