Demystifying JavaScript Variable Scope and Hoisting

 var test = "I'm global";
 
function testScope() {
  test = "I'm local";
 
  console.log(test);     
}
 
console.log(test);     // output: I'm global
 
testScope();           // output: I'm local
 
console.log(test);     // output: I'm local (the global variable is reassigned)

This time the local variable test overwrites the global variable with the same name. When we run the code inside testScope() function the global variable is reassigned. If a local variable is assigned without first being declared with the var keyword, it becomes a global variable. To avoid such unwanted behavior you should always declare your local variables before you use them. Any variable declared with the var keyword inside of a function is a local variable. It’s considered best practice to declare your variables.

I think that is untrue that you declare a new local variable within function scope without var statement. In this particular case you just reassign a global variable test.

All variables that can be used from the outside of scope is a global variable and all variables which is not declared with var statement is a global variable no matter that is within scope or not.

If you declare or assign a global variable within function scope without var statement it can only be used after the variable is declared / assigned from inside the function and it also can be used from outside the function scope after the function has been invoked like a common global variable that declared from the outside of function scope.

a = 0; // global variable
// similar with this
var a = 0; //global variable

var b; // declare a global variable
// b has no value yet
function globalFunc() {
    b = 0; // assign a global variable
    // now b has value 0 and ready to be used
}
// b has no value yet
globalFunc();
// now b has value 0 and ready to be used

function hasLocalVar() {
    var c = 0; // declare and assign a new local variable
    // c can be used here
}
// no variable c is found here
hasLocalVar();
// no variable c is found here