Table of contents
Definition
Nesting in programming is the concept where one piece of code is found within another. With this, the interpretation [→] or code execution is done in a step-in step-out approach where the nested code is executed and the results resurfaced above to be used by the code above.
Use case
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 example Javascript code shown, the printer
function is nested within a for
loop. This function is defined on a different line (17:19)
.
Each time an item in the fruits
array is looped over the function is called and its logic is executed.
Anything outside the loop
nest will not be executed until it is done. Thus done will only be printed to screen once the loop is done.
Summary
Nesting makes it possible to create somewhat isolated "context boxes" in other to componentise code execution. This idea is known as scoping [→].
Here is another article you might like 😊 What Is A Data Exchange Format?