DEV Community

Matt Eddy
Matt Eddy

Posted on • Edited on

Node.js - Modern JavaScript

Alt Text

This article is Part 3 of Working With NodeJS, 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
const x = [1, 2, 3, 4, 5];

let [y, z] = x;
console.log(y); // 1
console.log(z); // 2
Enter fullscreen mode Exit fullscreen mode

Use Case - x[0], x[1]

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

const { firstName, lastName } = user;
console.log(firstName); // John
console.log(lastName); // Doe
Enter fullscreen mode Exit fullscreen mode

Use Case - user.firstName and user.lastName

Conditional Initializing
const fee = isMember ? '$2.00' : '$10.00';
Enter fullscreen mode Exit fullscreen mode

Use Case - if/else

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

const obj2 = {
    id: 1,
    ...obj1
};
Enter fullscreen mode Exit fullscreen mode

Use Case - Object.assign({}, obj1);

Arrays

forEach to loop

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

Use Case - I want to loop through each index in the array and do something to it.

map a new array

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

Use Case - I want a new array containing new copies or changes of each array element.

filter an array

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

Use Case - I want a new array containing just the items I need.

reduce an array

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

Use Case - I want to reduce my array to a single value.

find an element in array


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

Enter fullscreen mode Exit fullscreen mode

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

some an array


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

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

The createUser and createBook have access to separate instances of the init functions closure scope.

Closure 2 - Another approach
 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
Enter fullscreen mode Exit fullscreen mode
Destructure Parameters
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);
Enter fullscreen mode Exit fullscreen mode

Classes

Classes and inheritance are available in 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();
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)