简体   繁体   中英

Can somebody explain the use of statement values Javascript ECMAScript?

I am new to Javascript and have noticed that statements have values:

> x = 1
<- 1

> if (false) {
    x=1;
  } 
  else { x=2 };
<- 2

Could somebody explain why statements have values what they are used for in real applications, since functions need to return values explicitly via return .

Is this related to the notion of completions, which are associated with values, irrespective of their type (Normal or Abrupt) ?

Normal completion values primarily come up in user code via eval , though even then it's not super common. The return value of eval is the final completion value of the executed statements. Since eval executes a list of statements, when you run eval("4") === 4 for instance, you're not evaluating an expression for a value specifically, automatic-semicolon-insertion is kicking in, so you're actually running eval("4;") and then getting the completion value of that statement.

In the future, completion-value semantics will also likely affect the do expression proposal which would allow for code like

const value = do {
  if (false) {
    1;
  } else { 
    2;
  }
};

value === 2;

You could almost look at your examples as a nice side-effect of the general completion value semantics in the language, as well. When you throw or return from a function, the spec language itself for instance, still traverses the whole function. Returning or throwing essentially says "the completion value is this value" with the type "return" or "throw". So if you had

function fn()
  if (false) {
    return 1;
  } else { 
    2;
  } 
}

one branch of the "if" produces an abrupt completion with value 1 , and the other produces a normal completion with a value 2 .

When execution (from the spec standpoint), gets to the end of the function itself, it will say "is this a return/throw, if so, propagate it to the caller of the function. If it is a normal completion, it will just discard the value and return undefined .

So really, the fact that there is a completion value is exactly the same as having a return value or throwing an exception value, from the standpoint of the spec, it just happens to discard the value in most cases if it is a non-abrupt completion.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM