Block Scope

Scope determines where variables are accessible. ES6 introduced block scoping with let and const.

var Problems (4 issues)

// 1. No block scope
if (true) { var x = 1 }
console.log(x) // 1 — leaks out of the block!

// 2. Hoisting
console.log(y)  // undefined (not ReferenceError!)
var y = 5

// 3. Re-declaration
var z = 1
var z = 2  // allowed — confusing!

// 4. Function scope only
function test() {
  var a = 1
}
console.log(a) // ReferenceError

let and const (ES6)

// Block-scoped
if (true) {
  let blockVar = 'inside'
  const blockConst = 'also inside'
}
// console.log(blockVar) // ReferenceError!

// No hoisting
// console.log(b)  // ReferenceError
let b = 5

// No re-declaration
let c = 1
// let c = 2  // SyntaxError

Global vs Local Scope

const global = 'I am global'

function example() {
  const local = 'I am local'
  console.log(global) // accessible
  console.log(local)  // accessible
}

console.log(global) // accessible
// console.log(local) // ReferenceError