Reputation: 1834
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) ?
Upvotes: 3
Views: 105
Reputation: 161597
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.
Upvotes: 5