232k views
5 votes
Write a JavaScript script that has subprograms nested three deep and in which each nested subprogram references variables defined in all of its enclosing subprograms.

2 Answers

1 vote

Final answer:

JavaScript Script with Nested Subprograms

Step-by-step explanation:

JavaScript Script with Nested Subprograms

JavaScript allows you to nest subprograms or functions inside one another.

Below is an example of a JavaScript script with three levels of nested subprograms:

function outerFunction() {
var outerVariable = 'Outer';

function middleFunction() {
var middleVariable = 'Middle';

function innerFunction() {
var innerVariable = 'Inner';

console.log(outerVariable, middleVariable, innerVariable);
}

innerFunction();
}

middleFunction();
}

outerFunction();

In this script, each subprogram references variables defined in its enclosing subprograms. The outerFunction has a variable called outerVariable, which is then accessed by the middleFunction. Similarly, the middleFunction has a variable middleVariable, which is accessed by the innerFunction.

User Pupsik
by
5.8k points
4 votes

Answer and Explanation:

Subprograms are nested three deep hence we would have three subprograms/functions under one program(function)

We call the program/function MotherFunction( using camel case variable naming rules)

function MotherFunction() {

var mother= 8;

console.log(mother);

function subDaughter1() {

var subDaughter1X = mother + 12;

console.log(subDaughter1X);

function subDaughter2() {

var subDaughter2X= mother + 5;

console.log(subDaughter2X);

function subDaughter3() {

var subDaughter3X= mother + 3;

console.log(subDaughter3X);

alert("sum="+subDaughter1X+subDaughter2X+subDaughter3X);

}

}

}

}

MotherFunction();

We created the first function and nested subfunctions under it, adding up the variable from the parent function(mother function) to its subfunctions and then alerting the total value of all the subfunction variables summed in the last/third subfunction. We then called the function after defining it.

User Vinod Vutpala
by
5.4k points