The code specification is divided into two camps: add semicolons and don’t add semicolons. Being familiar with the rules for automatic semicolon insertion helps you write code

Legal matching

The javascript interpreter matches the code sentence by sentence and inserts a semicolon if it is not valid. See the following example:

  var name = 'martin'
  var myName = name
Copy the code

Var name = ‘Martin’ is in compliance with THE JS syntax, but when the next token is in compliance with the JS syntax, var name = ‘Martin ‘var is in compliance with the JS syntax. So the interpreter automatically inserts a semicolon after ‘Martin’

Rules:

OnePart

Rule: javascript only concatenates the following five symbols (, [, +, -, /) with a space between them by default

Example:

  const myName = 'martin'
  const getName = myName
  (() = > { return 2 })
Copy the code

The above code will be translated into

  const myName = 'martin';
  const getName = myName(() = > { return 2 });
Copy the code

Const getName = myName (const getName = myName, const getName = myName, const getName = myName

SecondPart

Rule: javascript automatically inserts a semicolon after the return, throw, break, and continue lines

Example:

  function showName() {
      return
      const name = 'martin'
  }
Copy the code

The above code will be translated into

  function showName() {
      return;
      const name = 'martin';
  }
Copy the code

This will obviously result in a undefined return, and the code will not execute

ThirdPart

Rule: Semicolons are not added automatically to the for loop

Example:

  for (let i = 0 i < 10 i++) {}
Copy the code

Insert a semicolon after let I = 0, but the above code does not insert a semicolon automatically in the for loop, so it will give an Invalid or unexpected token when parsing

FourthPart

Rule: Automatically add a semicolon at the end of a line, a code block, or a program before the} mark

Example:

  if (true) {
    let name = 'martin'
  }
Copy the code

The above code will compile to

  if (true) {
    let name = 'martin';
  }
Copy the code

conclusion

There are pitfalls in writing code without semicolons, and being familiar with the insertion rules can help you avoid them

The issue of

🌲 mid-advanced front-end does not necessarily understand setTimeout | netease practice summary

80 lines of code to achieve Vue skeleton screen 🏆 | netease small practice

You misunderstood Vue nextTick

Stop saying Transition can’t Transition display