Hoisting vars

Yet Another Good Reason to use 'let' instead of 'var'

by asemahle

JavaScript

// Look at the following functions: SCENARIO_1 and 2.
// They look quite similar... 
// Can you predict what each one will output?
//
// (IMO, this is one of the many good reasons to use 'let' instead of 'var')
// (I mean... replacing 'var' with 'let' doesn't solve all problems, but at least you get an error)

function SCENARIO_1() {
	var a = "Hello";
  function f() {
  	console.log(a);
    a = "Peter";
    console.log(a);
  }
  f();
}

function SCENARIO_2() {
	var a = "Hello";
  function f() {
  	console.log(a);
    var a = "Peter";
    console.log(a);
  }
  f();
}

console.clear();
console.log('Running SCENARIO_1()...');
SCENARIO_1();

console.log('');

console.log('Running SCENARIO_2()...');
SCENARIO_2();