Global vs Local Scope

Photo by Jp Valery on Unsplash

Global vs Local Scope

How to learn and remember the difference between local and global scope in programming.

What is scope in software engineering terms? If we look up what scope means in the dictionary one of the terms that applies to programming is this. Scope is the amount of influence or treatment something has. If we apply it to computer science, we can start to get an idea of what global and local scope is.

I liken local scope to the laws of a particular country. Let's make up a place called Tribesk. One of the laws in Tribesk is each Saturday you must stand upon your head at 2pm in the afternoon. If you don't it's against the law.

If we take that same law and apply it across the whole Earth, it would not apply. Because each country is sovereign in its own right. Their laws do not necessarily reflect the same laws as anyone else.

Now taking a look at some code we can see with our law analogy how global and local scope are aligned.

let flower1 = blue let flower2 = pink

function flowersBloom() { let flowerBouquet = flower1 + flower2 console.log(flowerBouquet) }

flowersBloom()

console.log(flowerBouquet)

In the code above, our global scope is flower1 and flower2. They live in other countries than our function flowersBloom(). In the country of flowersBloom() we have a local scope for the variable flowerBouquet. Try the code out and see what error you receive in the console. Hopefully this helps you understand global and local scope in the realm of coding.