DEV Community

Discussion on: Instructions vs Expressions

Collapse
 
curtisfenner profile image
Curtis Fenner • Edited

This basic classification works for simple programs, but I think it misses the real divide by a bit. It would be difficult to classify a snippet like

let total = 0;
function accumulate(a, b) {
    return total += a + b;
}

console.log(accumulate(1, 2));
console.log(accumulate(1, 2));
// is `accumulate(1, 2)` "evaluated" or "executed"?
Enter fullscreen mode Exit fullscreen mode

Looking back at the clearer cases, there are also some problems:
Because you can write console.log(console.log(5)) at all, we must know that console.log(5) is in fact an expression, since function arguments are expressions (it simply evaluates to undefined). In fact, when you write something; what you're writing is called an "expression statement" which tells you to "execute" that expression.

You can observe that it is in fact "executing" the expression because expressions that you would otherwise want to call merely 'evaluated' take time to execute, they can throw errors, or they can hang and never let anything else execute.

You can make a much more fine-grained classification of expressions by identifying their side effects. A side effect is something that evaluation of an expression results in other than the value computed.

console.log has a side effect of printing something to the console.

accumulate from above has a side effect of increasing the total variable.

+ on its own is side-effect-free, sometimes called a "pure" expression.

This analysis is even more important in the context of languages with more expressive classification of values like Haskell, in which case you can precisely annotate most of the side-effects that each expression has. (Though, not whether or not they hang or throw errors)