Let’s talk about… the order of evaluation!
You might think you have a strong grasp on this concept, but many languages have their own nuanced take on evaluation order in some cases. And then JavaScript has “hoisting”, which kinda spits in the face of order of evaluation.
Before we dive in, here’s a short pop-quiz. What does this short program output when executed?
package main
import "fmt"
func init() {
fmt.Println("init")
}
var _ = func() int {
fmt.Println("var")
return 0
}()
func main() {
fmt.Println("main")
}
Answer below.
Order of Evaluation
At package level, initialization dependencies determine the evaluation order of individual initialization expressions in variable declarations. Otherwise, when evaluating the operands of an expression, assignment, or return statement, all function calls, method calls, receive operations, and binary logical operations are evaluated in lexical left-to-right order.
For example, in the (function-local) assignment
y[f()], ok = g(z || h(), i()+x[j()], <-c), k()
the function calls and communication happen in the order
f()
,h()
(ifz
evaluates tofalse
),i()
,j()
,<-c
,g()
, andk()
. However, the order of those events compared to the evaluation and indexing ofx
and the evaluation ofy
andz
is not specified, except as required lexically. For instance,g
cannot be called before its arguments are evaluated.
Alright. So there’s a lot of text there to say what mostly makes intuitive sense.
We can actually skip the first part about initialization dependencies and variable declarations. It’s interesting, but we’ll get to those details later. (It’s also where we get the answer to today’s quiz… but I’ll jump ahead and give you that answer anyway.)
The (artificially complex) example we’re shown is demonstrating the rest of that first paragraph. If your eyes glazed over the explanation following the example, take a moment to go back and read it. Trust me. It’s not as confusing as your brain thinks it is. And I could repeat it, but I’d be basically repeating the same thing, with more white space to fool your brain into think it’s less dense.
Done?
Not so bad, was it?
So what’s the answer to the quiz?
var
init
main
Not sure why? Stick around… we’ll be getting there soon 😉
Quotes from The Go Programming Language Specification Language version go1.22 (Feb 6, 2024)