Take a look at one of Github's star projects, 'Nocode', and make the following recommendations.Copy the code

No Code

No code is the best way to write secure and reliable applications. Write nothing; deploy nowhere.

Getting Started

Start by not writing any code.


Copy the code

This is just an example application, but imagine it doing anything you want. Adding new features is easy too:


Copy the code

The possibilities are endless.

Building the Application

Now that you have not done anything it’s time to build your application:


Copy the code

Yep. That’s it. You should see the following output:


Copy the code

Deploying

While you still have not done anything it’s time to deploy your application. By running the following command you can deploy your application absolutely nowhere.


Copy the code

I don’t know if you’ll get beaten to death by your colleagues, but you’ll get beaten to death by your boss that’s for sure.

Ok, the above is just a joke, here is attached the address of Nocode, you can have a look.

Now let’s get down to business. A lot of times we’ve had to change someone else’s code or add features to their code, and I’m sure that’s what most of us have in mind.


  1. Thank colleagues do not kill the grace, usually cast more feed some snacks.
  2. Write good code.

I personally hope you can calm down and carefully taste again, if you have a harvest, please give the author a thumbs up, let me know that there are people who get knowledge from here. Even if it’s trivial, you could waste eight precious minutes of your life.

Pledge to the Covenant ~~~~

Language specification

reference

Const and let are both block-level scopes, and var is function-level scopes

  • Use const for all immutable references and let, not var, for mutable references
// bad
var a = 1
var b = 2
if (b < 10) {
  b += 1
}

// good
const a = 1
let b = 2
if (count < 10) {
  count += 1
}
Copy the code
  • Chained assignment makes code less readable and is prohibited by convention
Is not recommendedletA = b = c = 1let a = 1
let b = 1
let c = 1
Copy the code

object

  • Create objects using literal values
// bad
const a = new Object{}

// good
const a = {}
Copy the code
  • Use the shorthand for the value of an object property
  • Add · comma · to the end of each line of an object property, as shown below
  • Append a semicolon to the declaration of a variable. Ignore this clause if you follow Standard specifications.
  • If there are unified specifications, ignore the preceding two.
const job = 'FrontEnd';

// bad
const item = {
  job: job
}

// good
const item = {
  job,
};
Copy the code

You can never be sure that this object will not be appended, so kindly fill in the commas on every line for your colleague. Otherwise, if your colleague happens to open a code check, he might kick your ass

An array of

  • Create an array using literal values
  • When adding elements to an array, use the push method
// bad
const items = new Array();
items[items.length] = 'test';


// good
const items = [];
items.push('test');

Copy the code
  • Using extended operators… Copy the array
const items = [];
const itemsCopy = [];
const len = items.length;
let i;

// bad
for (i = 0; i < len; i++) {
  itemsCopy[i] = items[i];
}

// good
itemsCopy = [...items];
Copy the code

B: well… I don’t think you’ll ever see a way to write bad anymore. Probably?

  • Use forEach, some, every, etc instead of the for loop
const items = [];
const len = items.length;

// bad
for (i = 0; i < len; i++) {
 // todo something for items[i]
}

// good
items.forEach((item, index) => {
    // todo something for items
});
Copy the code
  • When using the map method of an array, use a return declaration. In the case of a single declaration statement, omit the return declaration
// good
[1, 2, 3].map(x => {
  const y = x + 1
  return x * y
});

// good
[1, 2, 3].map(x => x + 1);
Copy the code
  • When using the reduce method of arrays, specify the initial value and use a return declaration. In the case of a single declaration statement, omit the return
// good
const flat = [[0, 1], [2, 3], [4, 5]].reduce((memo, item, index) => {
  const flatten = memo.concat(item)
  return flatten
}, []);
Copy the code

I know we’re all big shots here, but what if there’s something weird mixed in?

  • When using the filter method of arrays, use a single judgment that is guaranteed to always return false/true
// bad
inbox.filter((msg) => {
  const { subject, author } = msg
  if (subject === 'Mockingbird') {
    return author === 'Harper Lee'
  } else {
    return false
  }
})

// good
inbox.filter((msg) => {
  const { subject, author } = msg
  if (subject === 'Mockingbird') {
    return author === 'Harper Lee'
  }
  return false
})
Copy the code

Deconstruction assignment

  • Use destruct assignment when you need to use multiple attributes of an object
// bad
function getFullName (user) {
  const firstName = user.firstName
  const lastName = user.lastName

  return `${firstName} ${lastName}`
}

// good
function getFullName (user) {
  const { firstName, lastName } = user

  return `${firstName} ${lastName}`
}

// better
function getFullName ({ firstName, lastName }) {
  return `${firstName} ${lastName}`}Copy the code
  • Use deconstructed assignment as well when you need to use multiple values of an array
const arr = [1, 2, 3, 4]

// bad
const first = arr[0]
const second = arr[1]

// good
const [first, second] = arr
Copy the code
  • When a function needs to return multiple values, use object deconstruction instead of array deconstruction
// bad
function doSomething () {
  returnConst [top, xx, XXX, left] = const [top, xx, XXX, left] =doSomething()

// good
function doSomething () {
  returnConst {top, left} = {top, right, bottom, left}} const {top, left} =doSomething()
Copy the code

Classic case:

// When using the callback form, I often wonder if the first argument I define is err or data...function handle(){
    // todo something
    if(err){
        return [null,err];
    }
    // todo something
    return [data,err];
}

function handle1(){
    // todo something
    if(err){
        return [err,null];
    }
    // todo something
    return [err,data];
}
Copy the code

string

  • Use single quotation marks for strings.
// bad
const department = "JDC"

// good
const department = 'JDC'
Copy the code
  • When the string is too long, do not use the string concatenator \, but use + instead
const str = 'One key three links ~' +
  'key triple ~ triple ~' +
  'even ~'
Copy the code
  • When programmatically generating strings, use template strings
const test = 'test'

// bad
const str = ['a'.'b'.test].join()

// bad
const str = 'a' + 'b' + test

// good
const str = `ab${test}`
Copy the code
  • The standard method is used to read characters in a string
// Preferentially use string.charat (3) // instead of string[3]Copy the code

function

  • Instead of using arguments, choose to use…

Arguments is just an array of classes, and… It’s a real array

// good
function test(... args) {return args.join(' ')}Copy the code
  • Do not change the values of function arguments
// bad
function test (opts) {
  opts = opts || {}
}
// bad
function test1 (opts) {
  if(! ops){ ops = {}; } } // goodfunction test (opts = {}) {
  // ...
}
Copy the code

Coding standards

A single line of code block

  • Use Spaces in single-line blocks of code
/ / do not recommendfunction foo () {return true}
if(foo) {bar = 0} // Recommendedfunction foo () { return true }
if (foo) { bar = 0 }
Copy the code

I don’t recommend single-line blocks of code because you always have to append statements to them

Curly brace style

In programming, the brace style is closely related to the indentation style, and there are many ways to describe the position of the brace relative to a block of code. In JavaScript, there are three main styles, as follows:

// One True Brace Style
if (foo) {
  bar()
} else {
  baz()
}

// Stroustrup
if (foo) {
  bar()
}
else {
  baz()
}

// Allman
if (foo)
{
  bar()
}
else
{
  baz()
}
Copy the code

The first style is recommended. Note the Spaces around the braces and no Spaces at the end or header

Variable naming

When it comes to naming variables, there are two main camps: camel name and underline name.

Convention variables and parameters are named hump because of back-end development, supplementary convention database parameters are named underscore

The comma

  • Trailing commas in ECMAScript5 trailing commas are legal in object literals, but in IE8 (non-IE8 document mode) trailing commas throw an error.

Examples of trailing commas:

var foo = {
  name: 'foo',
  age: '22',}Copy the code

The nice thing about trailing commas is that they make it easier to add and remove elements from objects and arrays, and we only need to modify the new lines without increasing the number of differentiated lines of code.

Convention the trailing comma is recommended when the last element or attribute is on a different line from the closing parenthesis] or}. When in the same line, do not use trailing commas.

  • The comma Spaces

Spaces before and after commas improve code readability, and the team agreed to use Spaces after commas and not before commas.

Var foo = 1,bar = 2 var foo = 1,bar = 2 var foo = 1,bar = 2Copy the code

Make sure the comma is placed on the current line

Evaluates the whitespace of an attribute

Disallow whitespace in the computed properties of an object

It is recommended to use obj.foo if the attribute name does not contain a string requiring special processing, such as a hyphen

// do not recommend obj['foo' ]
obj[ 'foo']
obj[ 'foo'] // obj['foo']
Copy the code

Trailing newline

Trailing newlines in non-empty files is a common UNIX style that has the benefit of facilitating the prompt of the Shell when concatenating and appending files. In everyday projects, the benefit of keeping trailing line breaks is to reduce code conflicts during version control.

Is not recommendedfunction func () {
  // doRecommend something}function func () {
  // doSomething} // Here is a new lineCopy the code

That is, each file contains an empty line at the end

The indentation

Consistent indentation of code, as an engineer’s professional quality, is also to reduce merge conflicts to ensure that the convention uses Spaces to indent, and indent using two Spaces.

You can set the TAB to 2 Spaces by setting the IDE

Indent the key value of an object literal

There is a space between the colon and the value of a convention object literal

Var obj = {'foo' : 'haha'} var obj = {'foo': 'haha' }
Copy the code

Operator space

You need to add Spaces before and after the convention operators

Var sum = 1+2 is not recommendedCopy the code

Constructor starts with a capital letter

The convention distinguishes constructors from ordinary functions by capitalizing the first letter of constructors.

Class name uppercase is also certain ~

/ / do not recommend
var fooItem = new foo()

/ / recommend
var fooItem = new Foo()
Copy the code

A blank line

Blank lines are helpful for separating code logic, but too many empty lines can take up screen space and affect readability.

  • The maximum number of consecutive blank lines is 2
  • The first line inside a convention function is not empty
  • Convention uses blank line isolation between functions

The blank space

  1. Blocks of code should have Spaces around braces except at the beginning and end of each line

function foo () { return true } if (foo) {

  bar()

} else {

  baz()

}

  1. Add Spaces before and after the operator

const sum = 1 + 2

  1. Add Spaces after commas and colons

const cat = { name: nico, color: ‘white’ }

  1. Row level annotation//Add space before and after

const a = 1; // Define variable A

Style specification

Good programming style has a direct impact on your colleagues’ senses

annotation

Be sure to comment! Be sure to comment! Be sure to comment!

No matter what framework you use, what IDE you use, or whether you use TS, remember:

  • File, class, and function annotations must be usedJSDocSpecification, using /*content/ format, do not use // XXX mode.
  • A single line comment inside the method, with a separate line above the commented statement, using the // comment.
  • All enumerated type fields must have comments stating the purpose of each data item.
  • Instead of “half-assed” English annotations, it is better to use Chinese annotations to clarify the problem
  • Good naming and code structure are self-explanatory and do not use meaningless comments

No matter how busy you are, make sure you write notes, otherwise you won’t know what you think for a few months.

** @author XXX */ ** * sum function * @param {number} a * @param {number} b * @returns {number} sum */function sun(a, b) {
  return a + b;
}

Copy the code

Extraction function

  • Extract functional functions as far as possible from a single function
    • Operations on different types of data requested during page loading are separately extracted into functions -> to ensure that logic can be flexibly modified for each request
    • Page destruction needs to set the state operation extraction into functions, -> can ensure a unified entry, to prevent the omission of some operations
    • Operations that control component state are abstracted into functions -> to facilitate interception and appending operations in the flow
  • Don’t write a lot of statements directly in any of the framework’s lifecycle functions -> this will get you really kicked
  • Encapsulate functions where possible -> Requirements always change, you know
  • Data structures to consider future extensions of functionality -> ditto

Conditional statements

  • Conditional statements must have braces
// bad
function test (opts) {
  if(opts.length > 0)
    // todo something
  // todo other
}


// good
function test (opts) {
  if(opts.length > 0) {
      // todo something
  }
  // todo other
}
Copy the code

Defining utility classes

Define your own utility classes and try not to call third-party utility classes directly in business code. For example:

  • String processing: Determines whether a string conforms to the specification
  • Check whether it is a JSON object

Tip: please write a comment and tell everyone about your function, otherwise -> almost nothing

Comment out code carefully.

  • Explain in detail at the top, rather than simply commenting it out.
  • Deprecated methods or deprecated files must be commented or deleted

Sometimes I will encounter a long time to change the code results in no change bug, and then surprised to find that the method has been abandoned…

Finally, recommended method 3: TS/ESLint enables pre-live checking and passes if it fails

Please use it in new projects or you will beat yourself up


Above, as appropriate to comply with, the most important thing is that we are happy to write code

In the future, I will add the new place where I want to curse. Please give me three links with one button

Related series: Front End Foundation from scratch journey (super detailed, constantly updated ~)

Reference: guide. Aotu. IO/docs/js/cod… Alibaba Java Development Manual