If it's better to avoid declaring variables in the global scope, then when would we declare them there?


#1

Question

If it’s better to avoid declaring variables in the global scope, then when would we declare them there?

Answer

You’d primarily only be declaring variables in the global scope if there are certain variables that you need to access throughout your code across seperate inner scopes. You just want to define these commonly access variables in your global scope. Any variables that use these global variables in their own context can be made in its own scope so it doesn’t have to be shared across different scopes. You’ll learn about making inner block scopes in the next exercise. Basically, create your variables as low down in your scope as you can, but not too low that you can’t use them elsewhere where they’re needed. Example:

    	javascript
    	// x is used in the inner scopes myFunc, innerFunc, as well as in the global scope, so we'll define it globally here
    	let x = 2;
    	const myFunc = () {
    		// y is used in myFunc's scope and its inner innerFunc scope, so we'll declare it here
    		let y = 3;
    		console.log(x + y);
    		const innerFunc = () {
    			// z is only used in this innerFunc's scope so we'll only declare it here
    			let z = 4;
    			console.log(x + y + z);
    		}
    	};
    	console.log(x);