rwaldron / idiomatic.js

Principles of Writing Consistent, Idiomatic JavaScript
Other
24.66k stars 3.46k forks source link

Scope Block // 2.B.1.4 #224

Closed 2xSamurai closed 6 years ago

2xSamurai commented 6 years ago
// 2.B.1.4
// const and let, from ECMAScript 6, should likewise be at the top of their scope (block).

// Bad
function foo() {
  let foo,
    bar;
  if ( condition ) {
    bar = "";
    // statements
  }
}
// Good
function foo() {
  let foo;
  if ( condition ) {
    let bar = "";
    // statements
  }
}

Am i getting this wrong. Aren't we supposed to initialize the variables at the beginning of the scope. But here "bar" is declared inside "if", JavaScript doesn't have scope block right. So is this correct. Can someone explain this.

SidIcarus commented 6 years ago

Let has block scope. See

2xSamurai commented 6 years ago

thank you @SidIcarus