Where is the javascript code written? Where is the javascript code written?

Hello everyone, let me share with you which tag the javascript code is written in. Many people still don’t know this. Let’s explain it in detail below. Now let’s take a look!

Author: Yin Feng
Link: https://www.zhihu.com/question/20635785/answer/223515216

1. Avoid using js dregs and tasteless things

Over the years, with the development of HTML5 and Node.js, JavaScript has blossomed in various fields and has gone from “the most misunderstood language in the world” to “the most popular language in the world.” However, due to historical reasons, there are still some dregs and useless features in JavaScript language design, such as: global variables, automatic insertion of semicolons, typeof, NaN, false values, ==, eval, etc., which cannot be removed by the language, and developers must To avoid using these features, fortunately ESLint below can detect these features and give error prompts (if you encounter an interviewer who is still testing you for these features, you need to consider whether they are still in their project Using these features, you should also know how to answer this type of question) Deepl weight reduction.

2. Write concise JavaScript code

The following guidelines are from Robert C. Martin’s book “Clean Code” and apply to JavaScript. The entire list is very long. I have selected the part that I think is the most important and the part that I use the most in my projects. However, I still recommend that you read the original article. This is not a style guide, but a guide to using JavaScript to produce readable, reusable, and refactorable software.
variable

Use meaningful, readable variable names

Bad:

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

Good:

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

Define constants using ES6 const
The “constant” defined using “var” in the counterexample is mutable. When a constant is declared, the constant should be immutable throughout the program.

Bad:

var FIRST_US_PRESIDENT = "George Washington"

Good:

const FIRST_US_PRESIDENT = "George Washington"

Use an easily searchable name

We have much more code to read than we write, so it’s important that the code we write is readable and retrievable. Using meaningless variable names will make our programs difficult to understand and will hurt our readers, so please use searchable variable names. Tools like buddy.js and ESLint can help us find unnamed constants.

Bad:

// What the heck is 86400000 for?
setTimeout(blastOff, 86400000)

Good:

// Declare them as capitalized `const` globals.
const MILLISECONDS_IN_A_DAY = 86400000

setTimeout(blastOff, MILLISECONDS_IN_A_DAY)

Use descriptive variables (meaningful variable names)

Bad:

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)

method

Keep functions unitary

This is the most important rule in software engineering, when functions need to do more things, they will be harder to write, test, understand, and combine. When you can isolate a function to perform only one action, they will be easier to refactor and your code will be easier to read. If you strictly follow this rule, you will be ahead of many developers.

Bad:

function emailClients(clients) {
  clients.forEach(client => {
    const clientRecord = database.lookup(client)
    if (clientRecord.isActive()) {
      email(client)
    }
  })
}

Good:

function emailActiveClients(clients) {
  clients.filter(isActiveClient).forEach(email)
}

function isActiveClient(client) {
  const clientRecord = database.lookup(client)
  return clientRecord.isActive()
}

The function name should clearly indicate its function (see the name to know the meaning)
Bad:

function addToDate(date, month) {
  // ...
}

const date = new Date()

// It's hard to tell from the function name what is added
addToDate(date, 1)

Good:

function addMonthToDate(month, date) {
  // ...
}

const date = new Date()
addMonthToDate(1, date)

Use default variables instead of short-circuiting operations or conditions
Bad:

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

Good:

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

Function arguments (ideally no more than 2)

Limiting the number of function arguments is necessary to make testing functions easier. Too many parameters will make it difficult to use effective test cases to test each parameter of the function. Functions with more than three parameters should be avoided. Usually, more than three parameters means that the function is too complex, and you need to re-optimize your function. When multiple parameters are indeed needed, in most cases you can consider encapsulating these parameters into an object.
Bad:

function createMenu(title, body, buttonText, cancelable) {
  // ...
}

Good:

function createMenu({ title, body, buttonText, cancelable }) {
// ...
}

createMenu({
  title: 'Foo',
  body: 'Bar',
  buttonText: 'Baz',
  cancelable: true
})

Remove duplicate code
Duplicate code is the number one Bad Smell, so do whatever you can to avoid it. Because it means that when you need to modify some logic, there will be multiple places that need to be modified. Duplicate code is usually caused by two or more slightly different things that share most of the same thing, but their differences force you to use two or more separate functions to handle most of the same things. Removing duplicate code means creating an abstract function/module/class that can handle these differences.
Bad:

function showDeveloperList(developers) {
  developers.forEach(developer => {
    const expectedSalary = developer.calculateExpectedSalary()
    const experience = developer.getExperience()
    const githubLink = developer.getGithubLink()
    const data = {
      expectedSalary,
      experience,
      githubLink,
    }

    render(data)
  })
}

function showManagerList(managers) {
  managers.forEach(manager => {
    const expectedSalary = manager.calculateExpectedSalary()
    const experience = manager.getExperience()
    const portfolio = manager.getMBAProjects()
    const data = {
      expectedSalary,
      experience,
      portfolio,
    }

    render(data)
  })
}

Good:

function showEmployeeList(employees) {
  employees.forEach(employee => {
    const expectedSalary = employee.calculateExpectedSalary()
    const experience = employee.getExperience()

    const data = {
      expectedSalary,
      experience,
    }

    switch (employee.type) {
      case 'manager':
        data.portfolio = employee.getMBAProjects()
        break
      case 'developer':
        data.githubLink = employee.getGithubLink()
        break
    }

    render(data)
  })
}

avoid side effects
When a function does something other than “accept a value and return a result”, it is said to have a side effect. For example, writing a file, modifying global variables, or transferring all your money to a stranger, etc. In some cases, the program really needs side-effect behavior. In this case, these functions should be centralized together and do not use multiple functions/classes to modify a file. Use and only use one service to fulfill this requirement.
Bad:

const addItemToCart = (cart, item) => {
  cart.push({ item, date: Date.now() })
}

Good:

const addItemToCart = (cart, item) => {
  return [...cart, { item, date: Date.now() }]
}

Avoid conditional judgments
This seems unlikely. When most people hear this, their first reaction is: “How can we accomplish other functions without using if?” In many cases, the same purpose can be achieved by using polymorphism. The second question is the reason for this approach. The answer is what we mentioned before: keep the function single.

Bad:

class Airplane {
  // ...
  getCruisingAltitude() {
    switch (this.type) {
      case '777':
        return getMaxAltitude() - getPassengerCount()
      case 'Air Force One':
        return getMaxAltitude()
      case 'Cessna':
        return getMaxAltitude() - getFuelExpenditure()
    }
  }
}

Good:

class Airplane {
  // ...
}

class Boeing777 extends Airplane {
  // ...
  getCruisingAltitude() {
    return getMaxAltitude() - getPassengerCount()
  }
}

class AirForceOne extends Airplane {
  // ...
  getCruisingAltitude() {
    return getMaxAltitude()
  }
}

class Cessna extends Airplane {
  // ...
  getCruisingAltitude() {
    return getMaxAltitude() - getFuelExpenditure()
  }
}

Use new ES6/ES7 features

arrow function

Bad:

function foo() {
  // code
}

Good:

let foo = () => {
  // code
}

template string

Bad:

var message = 'Hello ' + name + ', it\'s ' + time + ' now'

Good:

const message = `Hello ${name}, it's ${time} now`

deconstruct

Bad:

var data = { name: 'dys', age: 1 }
var name = data.name,
    age = data.age

Good:

const data = {name:'dys', age:1}
const {name, age} = data 

Use ES6 classes instead of ES5 Functions

Typical ES5 classes (functions) are less readable in terms of inheritance, construction and method definition. When inheritance is needed, classes are preferred.
Good:

class Animal {
  constructor(age) {
    this.age = age
  }

  move() {
    /* ... */
  }
}

class Mammal extends Animal {
  constructor(age, furColor) {
    super(age)
    this.furColor = furColor
  }

  liveBirth() {
    /* ... */
  }
}

class Human extends Mammal {
  constructor(age, furColor, languageSpoken) {
    super(age, furColor)
    this.languageSpoken = languageSpoken
  }

  speak() {
    /* ... */
  }
}

Async/Await is a better choice than Promise and callbacks

Callbacks are untidy and create a lot of nesting. ES6 has Promises embedded, but async and await in ES7 outperform Promises. Promise code means: “I want to perform this operation and then use its result in another operation”. await effectively reverses the meaning, making it more like: “I want to get the result of this operation.” I like to use async/await whenever possible because it sounds simpler.

Bad:

require('request-promise')
  .get('https://en.wikipedia.org/wiki/Robert_Cecil_Martin')
  .then(function(response) {
    return require('fs-promise').writeFile('article.html', response)
  })
  .then(function() {
    console.log('File written')
  })
  .catch(function(err) {
    console.error(err)
  })

Good:

async function getCleanCodeArticle() {
  try {
    var request = await require('request-promise')
    var response = await request.get(
      'https://en.wikipedia.org/wiki/Robert_Cecil_Martin',
    )
    var fileHandle = await require('fs-promise')

    await fileHandle.writeFile('article.html', response)
    console.log('File written')
  } catch (err) {
    console.log(err)
  }
}

Babel

After the ES6 standard was released, front-end developers also gradually learned about ES6. However, due to compatibility issues, it has not been widely promoted. However, the industry has also used some compromise solutions to solve compatibility and development system issues. The most famous of them is Babel. Babel is a widely used transcoder. Its goal is to use Babel to convert all ES6 new syntax so that it can be executed in the existing environment.

Use next generation JavaScript, todayBabel

Not only can it convert ES6 code, it is also a testing ground for ES7. For example, it already supports async/await, making it easier for developers to write asynchronous code. The code logic and readability are simply not very good. Although it may take some time for mainstream browsers to support this asynchronous encoding method, based on Babel, developers can use it in production environments now. This is due to Babel’s strong alignment with the JavaScript technical committee and its ability to provide real-world implementations of new ECMAScript features before they are standardized. Therefore, developers can use a large number of unreleased or not widely supported language features in the production environment, and ECMAScript can also get real-world feedback before the specification is finalized. This positive feedback further promotes the development of the JavaScript language.

The simplest way to use Babel is as follows:

# Install babel-cli and babel-preset-es2015 plugins
npm install -g babel-cli
npm install --save babel-preset-es2015

Create the file .babelrc in the current directory and write:

{
  "presets": ['es2015']
}

ESLint

A high-quality project must contain a complete lint. If a project still has tabs, two spaces, and four spaces mixed in various styles, a function can easily have hundreds of lines, and there are several layers of if, nesting, and callbacks. Coupled with the various JavaScript dregs and tasteless things mentioned earlier, a strong urban-rural fringe trend is coming. How can I write code and adjust the code format every day?

How can this work? You have to write code well to get paid, so lint is very necessary, especially for large projects. It can ensure that the code conforms to a certain style and is at least readable, so that other people in the team can master it as soon as possible. Other people’s code. For JavaScript projects, ESLint would be a good choice at the moment. The installation process of ESLint will not be introduced. Please refer to the official website. The following is a very strict configuration of ESLint. This is the best response to the section on writing concise JavaScript code above.

{
  parser: 'babel-eslint',
  extends: ['airbnb', 'plugin:react/recommended', 'prettier', 'prettier/react'],
  plugins: ['react', 'prettier'],
  rules: {
    // prettier configuration for automated formatting code
    'prettier/prettier': [
      'error',
      {
        singleQuote: true,
        semi: false,
        trailingComma: 'all',
        bracketSpacing: true,
        jsxBracketSameLine: true,
      },
    ],
    // The complexity of a function does not exceed 10. All branches, loops, and callbacks added together do not exceed 10 in a function.
    complexity: [2, 10],
    // The nesting of a function cannot exceed 4 levels, multiple for loops, and deep if-else, these are the source of evil.
    'max-depth': [2, 4],
    //A function can have up to 3 levels of callbacks, using async/await
    'max-nested-callbacks': [2, 3],
    //A function can have up to 5 parameters. A function with too many parameters means that the function is too complex, please split it
    'max-params': [2, 5],
    //A function can have up to 50 lines of code. If it exceeds, please split it or simplify it.
    'max-statements': [2, 50],
    // Firm semicolon-less advocate
    semi: [2, 'never'],
  },
  env: {
    browser: true,
  },
}

Prettier

Prettier is a JavaScript formatting tool. It is inspired by refmt and has advanced support for ES6, ES7, JSX and Flow language features. By parsing JavaScript into AST and beautifying and printing based on AST, Prettier will lose almost all the original code style, thus ensuring the consistency of JavaScript code style. You can feel it first.

Automatically format code, no matter how messed up your original code format is, it will be formatted the same. This function is great, really great. We no longer need to worry about code format issues in the future.

After ESLint and Prettier are determined, they must be added to the pre commit hook. Because people are lazy, don’t expect all engineers to actively execute ESLint and Prettier, so the following .pre-commit file is created in package.json During postinstall of s, soft link to .git/hooks/pre-commit, so that the following script will be automatically executed during pre-commit. Try to add pre-commit hook at the initial stage of the project. If you add it in the middle of the project, you may encounter opposition from the team and it will be difficult to implement. This is also something you can pay attention to during the interview. We need practical means to improve efficiency and they need to be implemented.

#!/bin/sh

# git diff --cached --name-only --diff-filter=ACM command returns all the file names those are part of that commit (except deleted files). And, then grep '.js$' filters only the JavaScript files.

CHANGED_ASSETS="$(git diff --cached --name-only --diff-filter=ACM 2>/dev/null | grep '.js$' | xargs)"

if [ -n "${CHANGED_ASSETS}" ] then
# Prettify all staged .js files
    echo "$jsfiles" | xargs ./node_modules/.bin/prettier --write

# Add back the modified/prettified files to staging
    echo "$jsfiles" | xargs git add

    node_modules/.bin/eslint --fix ${CHANGED_ASSETS}
    exit $?
else
    exit 0
if

The above command will first perform Prettier formatting during pre-commit, and then perform ESLint verification. If you want to format the code while editing, Prettier also has plug-ins for current mainstream editors. Please refer to here. In addition, ESLint can be used well with Prettier. Refer to eslint-plugin-prettier. I have all the above configurations and files. I put it all into this project, and I really put a lot of effort into it so that everyone can write code well.

Use functional programming

Before talking about functional programming and its advantages, let’s first look at the disadvantages of our common programming method, imperative programming (imperative programming).

function getData(col) {
  var results = []
  for (var i = 0; i < col.length; i + + ) {
    if (col[i] & amp; & amp; col[i].data) {
      results.push(col[i].data)
    }
  }
  return results
}

This code is very simple. It filters an incoming array, takes out the data field of each element in it, and then inserts a new array and returns it. I believe many people will write similar code. It has many problems:

We are telling the computer how to complete one thing step by step, introducing a loop, and using an insignificant local variable i to control the loop (or iterator). In fact, I don’t need to care about how this variable starts, ends, or grows. This has nothing to do with the problem I want to solve.

We introduce a state results and continuously change this state. Its value will change every time it loops.

When our problem changes slightly, for example, I want to add a function that returns an array about the length of data, then we need to carefully study the existing code, figure out the entire logic, and then write a new function (in most cases, engineers The “copy-paste-edit” method will be enabled.

Such code has poor readability. Once the internal states exceed 10 and depend on each other, it is not easy to understand its logic.

Such code cannot be easily reused.

If it was functional programming, you would probably write:

function extract(filterFn, mapFn, col) {
  return col.filter(filterFn).map(mapFn)
}

Do you feel that the world is clean? This code is very concise and clear. If you understand filter / map, it is almost difficult to make mistakes. This is almost a general solution, a machine, with which you can solve any data set filtering and mapping problem. Of course, you can also be as abstract as:

function extract(filterFn, mapFn) {
  return function process(col) {
    return col.filter(filterFn).map(mapFn)
  }
}

Note that although the abstract results of the two are similar, their application scope is different. The latter is more like a production machine (function returns function), which further decouples the problem. This kind of decoupling not only generalizes the code, but also divides the execution process of the code into two stages, and also decouples the timing and interface. So, you can call extract in context A and process in context B to produce real results. Context A and context B can have nothing to do with each other. Context A only needs to provide filterFn and mapFn (for example, system initialization), and context B only needs to provide a specific data set col (for example, when a web request arrives). This timing decoupling greatly enhances the power of the code. Decoupling on the interface is like the universal socket used in travel, allowing your function to connect to the system in context A at one end and the system in context B at the other end.

At this point we can roughly see some characteristics of functional programming:
Author: Yin Feng
Link: https://www.zhihu.com/question/20635785/answer/223515216
Source: Zhihu
Copyright belongs to the author. For commercial reprinting, please contact the author for authorization. For non-commercial reprinting, please indicate the source.

Promote combination (composition), composition is the king.

Each function performs a single function as much as possible.

Block out the details and tell the computer what I want to do, not how to do it. When we look at filters/maps, they do not expose their own details. The implementation of a filter function may be a loop on a single-core CPU, or a dispatcher and aggregator on a multi-core CPU, but we can temporarily ignore its implementation details and only need to understand its functions.

Introduce no or as little status as possible.

When used properly, these features can bring the software:

Better design and implementation.

More clear and readable code. Since the state is greatly reduced, the code is easier to maintain and brings greater stability.

Better performance in distributed systems. Functional programming is generally abstracted at a higher level, and map/filter/reduce are its basic instructions. If these instructions are optimized for distribution, then the system can improve performance without any changes.

Makes lazy operations possible. In imperative programming, because you clearly tell the CPU how to operate step by step, the CPU can only obey orders, and the space for optimization has been squeezed; in functional programming, each function only encapsulates an operation and a set of data. It goes through a series of operations from input to output. If no one handles these outputs, the operation will not be actually executed.

The above excerpts are from Teacher Chen Tian’s Abstract Ability and Introduction to Functional Programming. This is just a glimpse, using a short case to demonstrate the power of functional programming. For many advanced concepts and in-depth learning, please refer to the original text.

Original location: How to write beautiful JavaScript code? – Know almost

refer to

clean-code-java

How to use a new language

Prettier

Introduction to Functional Programming

abstract ability

other

[My blog, welcome to communicate! ](http://rattenking.gitee.io/stone/index.html)

[My CSDN blog, welcome to communicate! ](https://blog.csdn.net/m0_38082783)

[WeChat Mini Program Column](https://blog.csdn.net/column/details/18335.html)

[Front-end notes column](https://blog.csdn.net/column/details/18321.html)

[DEMO download of WeChat applet implementing some Amap functions](http://download.csdn.net/download/m0_38082783/10244082)

[DEMO download of WeChat applet to achieve some effects of MUI](http://download.csdn.net/download/m0_38082783/10196944)

[GIT project address for WeChat applet to implement MUI](https://github.com/Rattenking/WXTUI-DEMO)

[WeChat Mini Program Example List](http://blog.csdn.net/m0_38082783/article/details/78853722)

[Front-end notes list](http://blog.csdn.net/m0_38082783/article/details/79208205)

[Game List](http://blog.csdn.net/m0_38082783/article/details/79035621)