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

Introduction to Linux File Compression and Packaging

1. Introduction to compression and packaging Comm...

JavaScript web page entry-level development detailed explanation

Part 3: ❤Three ways to overlook backend data rece...

Docker cleanup environment operation

Start cleaning carefully! List unused volumes doc...

CSS3 to achieve simple white cloud floating background effect

This is a very simple pure CSS3 white cloud float...

Detailed installation tutorial of mysql-8.0.11-winx64.zip

Download the zip installation package: Download a...

How to create a view on multiple tables in MySQL

In MySQL, create a view on two or more base table...

WeChat applet implements user login module server construction

I chose node.js to build the server. Friends who ...

MySQL 5.7.17 installation and configuration tutorial under Linux (Ubuntu)

Preface I have installed MySQL 5.6 before. Three ...

Solution to invalid margin-top of elements in div tags

Just as the title says. The question is very stran...

Detailed explanation of Vue life cycle functions

Table of contents Lifecycle Functions Common life...

Javascript closure usage scenario principle detailed

Table of contents 1. Closure 2. Closure usage sce...

404 error occurs when accessing the homepage of tomcat started in Docker mode

Scenario: When starting tomcat in docker (version...