EDDYMENS

Published 9 months ago

What Is Scoping In Programming?

Definition

Scoping in programming is the concept of creating isolated code blocks, very similar to the use of paragraphs to discuss different contexts of a story.

Example

Let's look at some examples in code:

01: 02: var fruits = ['Apple', 'Banana', 'Cherry', 'Orange', 'Mango'] 03: 04: var numberOfFruits = fruits.length 05: 06: for(var count = 0; numberOfFruits > count; count++) { 07: printer(fruits[count]) // <== output below: 08: } 09: 10: console.log("done") 11: 12: // output: 13: // Apple 5 14: // Banana 6 15: // Cherry 6 16: // Orange 6 17: // Mango 5 18: // done 19: function printer(item) { 20: console.log(item, item.length); 21: }

In the above code, we see the line printer(fruits[count]) (line 07) nested within a for loop. The for loop sets the scope and everything within it is done within context.

That means until the for loop is done the console log on line 10 will not execute. There is a second context which is within the printer function. Anything that happens within that function will stay there unless otherwise specified like console.log its results.

Here is another article you might like 😊 What Is Nesting In Programming?