Skip to content

Instantly share code, notes, and snippets.

@dherman
Created September 29, 2012 18:36
Show Gist options
  • Save dherman/3804848 to your computer and use it in GitHub Desktop.
Save dherman/3804848 to your computer and use it in GitHub Desktop.
temporary dead zone
// ---------------------------------------------------------------------
// 1. UNCONTROVERSIAL AMONGST TC39
// ---------------------------------------------------------------------
// read before write throws
{
console.log(x); // throws
let x = 12;
console.log(x);
}
// functions are initialized on entry to block
{
console.log(f); // prints function
function f() { }
}
// read before write throws even if it syntactically looks like the
// assignment happens before any read
{
f(); // throws
let x = 12;
function f() { return x } // tries to read local x
}
// read before write throws even if there's all sorts of crazy control
// flow that makes it totally unclear syntactically whether that's going
// to happen; hence the term "temporal" -- the variable is dead for the
// time period between when it's in scope and when it's first initialized
{
// might or might not call f
function helper(callback) {
if (Math.random() < 0.5) {
return callback();
}
return "didn't feel like calling the callback";
}
{
helper(f); // throws iff helper calls f
let x = 12;
function f() { return x; } // tries to read local x
}
}
// ----------------------------------------------------------------------
// 2. CONTROVERSIAL, i.e., DAVE HATES IT :)
// ----------------------------------------------------------------------
// *only* allowed to be initialized with the syntactic initializer
{
x = "initialized"; // throws
let x = "foobar";
}
// legal:
{
let x = foo() ? bar() : baz();
}
// illegal:
{
let x;
if (foo()) {
x = bar(); // throws
} else {
x = baz(); // throws
}
}
@stevemao
Copy link

stevemao commented Sep 2, 2016

// illegal:
{
    let x;
    if (foo()) {
        x = bar(); // throws
    } else {
        x = baz(); // throws
    }
}

is it because bar and baz are undefined?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment