I am going to write a series of js skills, which mainly summarizes various practical tips and tips for js. This article mainly studies how to make our functions clearer.
Use deconstruction of object parameters
If you want the function to receive many parameters (if more than two), then you should use the object. On this basis, the required parameters can be extracted using deconstructive syntax.
Ordinary writing
const greet = (obj) => { return `${}, ${}${}`; }
rewrite
const greet = ({ greeting, firstName, lastName }) => { return `${greeting}, ${firstName}${lastName}`; }
Using the deconstruction method will be more elegant, and we can write less repetitive things, and the naming will be clearer.
Named callback functions
Good naming will make reading code easier, and so will callback functions be named.
Ordinary 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 separately, you can better see the meaning of the code at a glance, as above: It is obvious from the name that the callback function is used to double each element of the original array.
Make the conditional sentence descriptive
For complex conditional judgments, we can use functions to represent them alone, which will make the conditional statement more descriptive.
Ordinary writing
if (score === 100 || remainingPlayers === 1 || remainingPlayers === 0) { quitGame(); }
rewrite
const winnerExists = () => { return score === 100 || remainingPlayers === 1 || remainingPlayers === 0 } if (winnerExists()) { quitGame(); }
According to the original writing method, we have long expressions in brackets, but it is not easy to see what it is judging. After rewriting, we put it in a named function, and we can roughly see 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
Ordinary 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 of a given prop value, we can achieve the same effect using just one object.
Map rewrite
const map = new Map([['a', 1], ['b', 2], ['c', 3]]) const val = ('a')
When using Map, the code is much shorter. We pass an array with each item in the array containing the key and the value. Then we only use the get method of the Map instance to get the value from the key. One advantage of Map over objects is that we can use numbers, booleans, or other values like objects as keys. The object can only use strings or symbols as keys.
Use Set default properties
Ordinary writing
const menuConfig = { title: null, body: 'Bar' }; function createMenu(config) { = || 'Foo'; = || 'Bar'; } createMenu(menuConfig);
rewrite
const menuConfig = { title: 'Order', body: 'Send' }; function createMenu(config) { config = ({ title: 'Foo', body: 'Bar' }, config); // config : {title: "Order", body: "Bar"} // ... } createMenu(menuConfig);
Delete duplicate code, merge similar functions; 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 ); // Make the jump function independent};
Refining functions
If a function is too long and has to add several comments to make the function appear easier to read, then it is necessary to refactor these functions.
If there is a piece of code in the function that can be independent, then we'd better put these codes into another independent function.
Example
For example, in a function responsible for obtaining user information, we also need to print a log related to user information.
var getUserInfo = function(){ ajax( 'http:// /userInfo', function( data ){ ( 'userId: ' + ); ( 'userName: ' + ); ( 'nickName: ' + ); }); };
rewrite
We can encapsulate the statement that prints the log in an independent function.
var getUserInfo = function(){ ajax( 'http:// /userInfo', function( data ){ printDetails( data ); }); }; var printDetails = function( data ){ ( 'userId: ' + ); ( 'userName: ' + ); ( 'nickName: ' + ); };
Quote reference:JavaScript Refactoring Tips — Making Functions Clearer and Cleaner"JavaScript Design Patterns and Development Practice"
Summarize
This is the end of this article about how to make your JavaScript functions more elegant. For more relevant content on JavaScript functions, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!