Can this part seems to catch of set quite a few. Why do we have a variable that cannot be defined outside of a function for?
Your code so far
function myLocalScope() {
// Only change code below this line
var myVar = "Help"
console.log('inside myLocalScope', myVar);
}
myLocalScope();
// Run and check the console
// myVar is not defined outside of myLocalScope
console.log('outside myLocalScope', myVar);
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.96 Safari/537.36 Edg/88.0.705.56.
I’m not sure I completely understand. I think you’re asking “What do we need local variables? Why can’t we use globals?”
Yes, global variables would work. But there are reasons why we avoid them:
They can get messy. In really large code bases, it can be difficult if the variable is defined 200 lines above.
If the variable is only needed in that function, it makes sense for that function to take care of it.
You don’t want to pollute the scope with too many variables. This can become confusing and can cause bugs if you accidentally try to use the same variable twice, or if you have similar sounding variables and get confused.
Pure functions are ideal. Ideally a function should only depend on what is passed into it, not variables from the parent scope (unless they are passed in as parameters). This makes functions easier to debug, reuse, and test.
That’s not to say that you never use a global variable. One example would be a constant. If I have a constant like:
const CIRCUMFERENCE_OF_EARTH_IN_KM = 40074;
It doesn’t make sense to pass that in as a parameter because it’s never going to change. Constants like this are good candidates for globals. There have been a few other cases where I have used a global variable, but I tend to avoid it when I can.