In JavaScript, what code executes at runtime and what code executes at parsetime?

randomable picture randomable · Oct 26, 2010 · Viewed 10.8k times · Source

With objects especially, I don't understand what parts of the object run before initialization, what runs at initialization and what runs sometime after.

EDIT: It seems that parsetime is the wrong word. I guess I should have formulated the question "In the 2-pass read, what gets read the first pass and what gets read the second pass?"

Answer

Gareth picture Gareth · Oct 26, 2010

A javascript file is run in a 2-pass read. The first pass parses syntax and collects function definitions, and the second pass actually executes the code. This can be seen by noting that the following code works:

foo();

function foo() {
  return 5;
}

but the following doesn't

foo(); // ReferenceError: foo is not defined

foo = function() {
  return 5;
}

However, this isn't really useful to know, as there isn't any execution in the first pass. You can't make use of this feature to change your logic at all.