In line 10  to clearTimeout() function there is passed timer variable which is decleared outside moveBox function and under it in the line 20. Why does the java script resolves timer to a variable? Why it does see it?

In line 10  to clearTimeout() function there is passed timer variable which is decleared outside moveBox function and under it in the line 20. Why does the java script resolves timer to a variable? Why it does see it?

 
    
    Variable declarations in JavaScript are processed before any step-by-step code in that scope, and functions declared inside other functions (and in the global scope) have access to variables declared in their containing scope.
So the variable exists because the declaration is processed beforehand, and the function has access to it because that's how scope works in JavaScript.
So what happens in your code happens in this order:
Variables speed, moveBox, and timer are all declared and given the initial value undefined.
Step by step code execution begins
speed is assigned the value 10
The function expression on the right of the moveBox = is evaluated and the resulting function reference is assigned to moveBox.
The function expression being passed into setInterval is evaluated, and then setInterval is called with it and the value of speed.
The return value of setInterval is assigned to timer
(Some time later) The first call to moveBox occurs
