concept global scope in category angular

This is an excerpt from Manning's book Getting MEAN with Mongo, Express, Angular, and Node.js 2ED.
This piece of code throws an error because it’s trying to use the variable surname in the global scope, but it was defined in the local scope of the function addSurname(). A good way to visualize the concept of scope is to draw some nested circles. In figure D.1, the outer circle depicts the global scope; the middle circle depicts the function scope; and the inner circle depicts lexical scope. You can see that the global scope has access to the variable firstname and that the local scope of the function addSurname() has access to the global variable firstname and the local variable surname. In this case, lexical scope and function scope overlap.
If you want the global scope to output the full name while keeping the surname private in the local scope, you need a way of pushing the value into the global scope. In terms of scope circles, you’re aiming for what you see in figure D.2. You want a new variable, fullname, that you can use in both global and local scopes.
One way you could do it—and we’ll warn you now that it’s bad practice—is to define a variable against the global scope from inside the local scope. In the browser, the global scope is the object window; in Node.js, it’s global. Sticking with browser examples for now, the following listing shows how this would look if you updated the code to use the fullname variable.
Listing D.4. Global fullname variable
const firstname = 'Simon'; const addSurname = function () { const surname = 'Holmes'; window.fullname = firstname + ' ' + surname; #1 console.log(fullname); }; addSurname(); console.log(fullname); #2This approach allows you to add a variable to the global scope from inside a local scope, but it’s not ideal. The problems are twofold. First, if anything goes wrong with the addSurname() function and the variable isn’t defined, when the global scope tries to use it, you’ll get an error thrown. The second problem becomes obvious when your code grows. Suppose that you have dozens of functions adding things to different scopes. How do you keep track of them? How do you test them? How do you explain to someone else what’s going on? The answer to all these questions is with great difficulty.