How to make your JavaScript functions more elegant

How to make your JavaScript functions more elegant

I am going to write a series of js skills, which is mainly to summarize various practical tips and tricks of js. This article mainly studies how to make our functions clearer.

Object parameters using destructuring

If you want your function to take many arguments (more than two), you should use an object. On this basis, the required parameters can be extracted using deconstruction syntax.

Normal writing

const greet = (obj) => {
  return `${obj.greeting}, ${obj.firstName}${obj.lastName}`;
}

rewrite

const greet = ({
  greeting,
  firstName,
  lastName
}) => {
  return `${greeting}, ${firstName}${lastName}`;
}

Using deconstruction will be more elegant, and we can also write less repetitive things, and the naming will be clearer.

Naming callback functions

Good naming makes it easier to read code, and the same goes for naming callback functions.

Normal writing

const arr = [1, 2, 3].map(a => a * 2);

rewrite

const double = a => a * 2;
const arr = [1, 2, 3].map(double);

By naming them separately, it is easier to see the meaning of the code at a glance, as shown above: From the name, it is obvious that the callback function is used to double each element of the original array.

Make conditionals descriptive

For complex conditional judgments, we can use functions alone to express them, which will make the conditional statement more descriptive.

Normal writing

if (score === 100 || remainingPlayers === 1 || remainingPlayers === 0) {
    quitGame();
  }

rewrite

const winnerExists = () => {
  return score === 100 ||
    remainingPlayers === 1 ||
    remainingPlayers === 0
}
if (winnerExists()) {
  quitGame();
}

As written originally, we have a long expression in parentheses, but it is hard to tell what it is judging. After rewriting, we put it in a named function, and we can roughly understand the meaning of the expression based on the name.

Replace switch statements with Map or Object

When your switch statement is long, it means you should simplify your code.

Normal writing

const getValue = (prop) => {
  switch (prop) {
    case 'a': {
      return 1;
    }
    case 'b': {
      return 2;
    }
    case 'c': {
      return 3;
    }
  }
}
const val = getValue('a');

Object rewrite

const obj = {
  a: 1,
  b: 2,
  c: 3
}
const val = obj['a'];

We use switch to nest multiple blocks with multiple return statements just to get the return value for a given prop value, but we can achieve the same effect using just one object.

Map Rewrite

const map = new Map([['a', 1], ['b', 2], ['c', 3]])
const val = map.get('a')

When using Map, the code is also much shorter. We pass an array where each item contains a key and a value. Then we just use the get method of the Map instance to get the value from the key. One benefit of Map over Object is that we can use other values ​​like numbers, Booleans or objects as keys. Objects can only have strings or symbols as keys.

Using Object.assign to set default properties

Normal writing

const menuConfig = {
  title: null,
  body: 'Bar'
};
function createMenu(config) {
  config.title = config.title || 'Foo';
  config.body = config.body || 'Bar';
}
createMenu(menuConfig);

rewrite

const menuConfig = {
  title: 'Order',
  body: 'Send'
};
function createMenu(config) {
  config = Object.assign({
    title: 'Foo',
    body: 'Bar'
  }, config);
  // config : {title: "Order", body: "Bar"}
  // ...
}
createMenu(menuConfig);

Delete duplicate code, merge similar functions, and delete deprecated code

Bad writing

var paging = function( currPage ){
    if ( currPage <= 0 ) {
        currPage = 0;
        jump( currPage ); // jump }else if ( currPage >= totalPage ){
        currPage = totalPage;
        jump( currPage ); // jump }else{
        jump( currPage ); // jump }
};

rewrite

var paging = function( currPage ){
    if ( currPage <= 0 ) {
        currPage = 0;
    }else if ( currPage >= totalPage ){
        currPage = totalPage;
    }
    jump( currPage ); // separate the jump function };

Extraction function

If a function is too long and requires several comments to make it easier to read, then it is necessary to refactor these functions.

If there is a section of code in a function that can be isolated, it is best to put this code into another independent function.

Example

For example, in a function responsible for obtaining user information, we also need to print logs related to user information.

var getUserInfo = function(){
    ajax( 'http:// xxx.com/userInfo', function( data ){
        console.log( 'userId: ' + data.userId );
        console.log( 'userName: ' + data.userName );
        console.log( 'nickName: ' + data.nickName );
    });
};

rewrite

We can encapsulate the print log statement in a separate function.

var getUserInfo = function(){
    ajax( 'http:// xxx.com/userInfo', function( data ){
        printDetails( data );
    });
};

var printDetails = function( data ){
    console.log( 'userId: ' + data.userId );
    console.log( 'userName: ' + data.userName );
    console.log( 'nickName: ' + data.nickName );
};

Reference: JavaScript Refactoring Tips — Making Functions Clearer and Cleaner "JavaScript Design Patterns and Development Practices"

Summarize

This is the end of this article on how to make your JavaScript function more elegant. For more related content about elegant JavaScript functions, please search for previous articles on 123WORDPRESS.COM or continue to browse the related articles below. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • An article teaches you JS function inheritance
  • What is the length of a function in js?
  • JavaScript Basics Series: Functions and Methods
  • Use of JavaScript sleep function
  • Exception handling of built-in functions json_encode and json_decode in php
  • Summary of 50+ Utility Functions in JavaScript
  • In-depth understanding of JavaScript callback functions
  • Three solutions for sub-functions accessing external variables in JavaScript
  • JavaScript functional programming basics

<<:  How to build pptpd service in Alibaba Cloud Ubuntu 16.04

>>:  Detailed explanation of how to use amoeba to implement read-write separation of MySQL database

Recommend

Two ideas for implementing database horizontal segmentation

introduction With the widespread popularity of In...

Solution to Vue data assignment problem

Let me summarize a problem that I have encountere...

A detailed introduction to setting up Jenkins on Tencent Cloud Server

Table of contents 1. Connect to Tencent Cloud Ser...

Even a novice can understand the difference between typeof and instanceof in js

Table of contents 1. typeof 2. instanceof 3. Diff...

Window.name solves the problem of cross-domain data transmission

<br />Original text: http://research.microso...

My personal summary of mysql 5.7 database installation steps

1.mysql-5.7.19-winx64.zip (this is the free insta...

What are the benefits of semantic HTML structure?

one: 1. Semantic tags are just HTML, there is no ...

Implementation of Jenkins+Docker continuous integration

Table of contents 1. Introduction to Jenkins 2. I...

Reasons why MySQL 8.0 statistics are inaccurate

Preface Whether it is Oracle or MySQL, the new fe...