Q:

Isolate scope in javascript

I am getting results not expected with javascript variable redefined. I looked up that variable scope is not isolated so my question is, how can it be isolated so as to not cause conflictions with other code.
var test = "value";
var a = true;
if(a){
  console.log(test);
  var test = "another";
  console.log(test);
}
console.log(test);

Most would expect:
value
another
value

but actual:
value
another
another

A:

Variables declared with var are function scoped.
If you want block scope, ES6 introduces let:
let test = "value";
let a = true;
if(a) {
  console.log(test); // ReferenceError
  let test = "another";
  console.log(test); // "another"
}
console.log(test); // "value"

But let variables are still hoisted. So if you reference before iniltialization (temporal dead zone), you will get a ReferenceError instead of the value in the parent scope.

