📜 ⬆️ ⬇️

Pure javascript. Variables

Translation of the book by Ryan McDermott clean-code-javascript .

Table of contents:



image

Use meaningful and pronounced variable names.


Poorly:

const yyyymmdstr = moment().format('YYYY/MM/DD'); 

Good:

 const yearMonthDay = moment().format('YYYY/MM/DD'); 

Use the same method for the same type of variable.


Poorly:
')
 getUserInfo(); getClientData(); getCustomerRecord(); 

Good:

 getUser(); 

Use Named Values


We will read the code more often than we ever write. It is important to write readable code that is easy to find. Make your names searchable. Tools like buddy.js and ESLint can help identify unnamed constants.

Poorly:

 //   86400000? setTimeout(blastOff, 86400000); 

Good:

 //     . const MILLISECONDS_IN_A_DAY = 86400000; setTimeout(blastOff, MILLISECONDS_IN_A_DAY); 

Use explanatory variables.


Poorly:

 const address = 'One Infinite Loop, Cupertino 95014'; const cityZipCodeRegex = /^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$/; saveCityZipCode( address.match(cityZipCodeRegex)[1], address.match(cityZipCodeRegex)[2] ); 

Good:

 const address = 'One Infinite Loop, Cupertino 95014'; const cityZipCodeRegex = /^[^,\\]+[,\\\s]+(.+?)\s*(\d{5})?$/; const [, city, zipCode] = address.match(cityZipCodeRegex) || []; saveCityZipCode(city, zipCode); 

Use humanized names


Explicit is better than implicit.

Poorly:

 const locations = ['Austin', 'New York', 'San Francisco']; locations.forEach((l) => { doStuff(); doSomeOtherStuff(); // ... // ... // ... //   `l`? dispatch(l); }); 

Good:

 const locations = ['Austin', 'New York', 'San Francisco']; locations.forEach((location) => { doStuff(); doSomeOtherStuff(); // ... // ... // ... dispatch(location); }); 

Do not add unnecessary context.


If your class / object name tells you what it is, do not repeat the same when naming its properties and methods.

Poorly:

 const car = { carMake: 'Honda', carModel: 'Accord', carColor: 'Blue' }; function paintCar(car) { car.carColor = 'Red'; } 

Good:

 const car = { make: 'Honda', model: 'Accord', color: 'Blue' }; function paintCar(car) { car.color = 'Red'; } 

Use default conditions instead of short circuits or conditional expressions.


Poorly:

 function createMicrobrewery(name) { const breweryName = name || 'Hipster Brew Co.'; // ... } 

Good:

 function createMicrobrewery(breweryName = 'Hipster Brew Co.') { // ... } 

Source: https://habr.com/ru/post/319476/


All Articles