JavaScript only has function scope; each function has a scope chain that directly reaches the window object.
The search of variables is searched from the inside to the outside layer, and it will stop when it is found.
At the same time, it can not only find and use, but also change external variables.
The code copy is as follows:
var color = "blue";
function changeColor() {
var anotherColor = "red";
function swapColors() {
var tempColor = anotherColor;
anotherColor = color;
color = tempColor;
}
swapColors();
}
changeColor();
console.log(color); // "red" external variables can not only be accessed but also modified