Zimzalabim
Zimzalabim

Reputation: 1137

Scope of try declared variable

Looking at this code, in prototype function onDiagram line 30 we have:

proto.onDiagram = function (message, address) {
  message = this.arrayBufferToString(message);
  try {
    var obj = JSON.parse(message);
  } catch (e) {
    return;
  }
  if (!obj) {
    return;
  }
  switch (obj.type) {
    ...

Would not obj be local to try here? Would expected the code to be:

var obj;
try {
   obj = JSON.parse(message);
} catch (e) {
   ...

Upvotes: 1

Views: 930

Answers (1)

James Allardice
James Allardice

Reputation: 165971

Would not obj be local to try here?

No. The declaration gets hoisted (as do all declarations) to the top of the execution context. The code is effectively interpreted as you have shown in your second example. Until a value is assigned to obj it implicitly has the value undefined.

JavaScript (ES5, anyway) does not have block scope so it's not possible to contain a variable declaration to a try block. It will always be visible to the enclosing function.

Upvotes: 3

Related Questions