Anonymous
Anonymous

Reputation: 121

How to call functions with parameters within a nested function?

Let's say I have a nested function named countries and I want to call two functions with one named Russia with parameter named cities1 and another named China with parameter named cities2 within the function countries. How do I call the two functions with parameters within a nested function?

function countries() {
  function Russia(cities1) {
    var totalpop1 = cities1 * (10 ** 6);
    //each city has a population of 10^6 people
    return totalpop1;
  }

  function China(cities2) {
    var totalpop2 = cities2 * (10 ** 6);
    //each city has a population of 10^6 people
    return totalpop2;
  }
  var result = totalpop1 + totalpop2;
  return result;
}

Upvotes: 1

Views: 1201

Answers (1)

Pablo Darde
Pablo Darde

Reputation: 6412

I think you can use an Object (like a Class).

What about the code below?

var countries = {
  getRussia: function(cities1) {
    var totalpop1 = cities1 * (10 ** 6);
    //each city has a population of 10^6 people
    return totalpop1;
  },

  getChina: function(cities2) {
    var totalpop2 = cities2 * (10 ** 6);
    //each city has a population of 10^6 people
    return totalpop2;
  },
  
  getTotal: function(pop1, pop2) {
    var result = this.getRussia(pop1) + this.getChina(pop2);
    return result;
  }
}

var div = document.querySelector("#result");
div.innerHTML = countries.getTotal(1, 4);
<div id="result"></div>

But if you really want to call nested funcions you could use closures:

function countries() {
    return function(cities1) {
    var totalpop1 = cities1 * (10 ** 6);

    return function(cities2) {
        var totalpop2 = cities2 * (10 ** 6);

      return totalpop1 + totalpop2;
    }
  }
}

var div = document.querySelector('#result');

div.innerHTML = countries()(1)(4);

Upvotes: 2

Related Questions