1

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;
}
2
  • 1
    Well, you first have to call the inner functions, but you aren't showing what you call them with in the code above Commented Oct 30, 2018 at 23:31
  • 2
    If you call it from within countries, then simply Russia(809). If outside of countries, then you can't reach nested functions because of scope Commented Oct 30, 2018 at 23:37

1 Answer 1

2

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);
Sign up to request clarification or add additional context in comments.

2 Comments

What is the purpose behind using 'this' keyword?
the this keyword binds the Object countries in ECMA 5. If the function was outside the object, the this keyword would bind the function itself.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.