Understand JS execution in the stack

It is clear from the figure above that when executing the code on the left:

  1. Create an execution stack in storage space
  2. The EC(global) execution context stores the basic type value a, and since the function is a reference type, space is created on the heap at address AB1 for foo
  3. When fn is executed, a new EC (foo) context is opened, which stores the corresponding parameters and variables. The definition of baz involves the function baz, so a new storage space is opened at AB2 and baz is returned
  4. When fn(3) is called, the new execution context EC(baz) is opened and the corresponding result is 7
  5. At the end of code execution, EC (baz) is recycled because there is no corresponding call.

Reduce the level of judgment

// Code module 1
function doSomething (part, chapter) {
  const parts = ['ES2016'.'engineered'.'Vue'.'React'.'Node']
  if (part) {
    if (parts.includes(part)) {
      console.log('Belongs to current course')
      if (chapter > 5) {
        console.log('You need to provide VIP status')}}}else {
    console.log('Please confirm module information')
  }
}

doSomething('ES2016'.6)

// Code module 2
function doSomething (part, chapter) {
  const parts = ['ES2016'.'engineered'.'Vue'.'React'.'Node']
  if(! part)return console.log('Please confirm module information')
  if(! parts.includes(part))return console.log('Belongs to current course')
  if (chapter > 5) console.log('You need to provide VIP status')
}

doSomething('ES2016'.6)
Copy the code
  • Compare code module 1, code module 2. It’s easy to see in code 2,More logical thinking, more concise statements. Compare in JSBench, module 2Performance is also higherBecause there are no layers of nested judgment.
  • When writing a judgment condition, you can useReverse judgmentThe way of