0

I was trying to understand Function Scope vs Gobal Scope, with the below example:

<script>
// The following variables are defined in the global scope
var num1 = 2,
    num2 = 3,
    name = "Chamahk";

// This function is defined in the global scope
function multiply() {
  return num1 * num2;
}

console.log(multiply()); // Returns 60

// A nested function example
function getScore () {
  var num1 = 20,
      num2 = 30;

  function add() {
    var num1 = 200,
      num2 = 300;
    return name + " scored " + (num1 * num2);
  }

  return add();
}

console.log(getScore()); // Returns "Chamahk scored 60000"
</script>

I googled and found that Global Scoped variable can be accessed using this. changing the return code to

return name + " scored " + (this.num1 * this.num2);

gave output as "Chamahk scored 6", means this is accessing the global var num1 and num2.

This is clear, but what i wanted to know, how to access the num1 and num2 declared in getScore() function .i.e. to get the output as 600.

tonymarschall
  • 3,862
  • 3
  • 29
  • 52

1 Answers1

0

I have to say your question is a little confusing.

Generally you would want to use parameters to your functions, to pass values around.

The reason you are getting 60000, is because in your add function you are setting num1, and num2 to 200 and 300.

If you changed your add function to take num1, and num2 as parameters, and not redeclare them, you could pass in your values in getScore();

e.g return add(num1, num2);

<script>
// The following variables are defined in the global scope
var num1 = 2,
    num2 = 3,
    name = "Chamahk";

// This function is defined in the global scope
function multiply(num1, num2) {
  return num1 * num2;
}

console.log(multiply(num1, num2)); // Returns 6!!!

// A nested function example
function getScore () {
  var num1 = 20,
      num2 = 30;

  function add(num1, num2) {
    return name + " scored " + (num1 * num2);
  }

  return add(num1, num2);
}

console.log(getScore()); // Returns "Chamahk scored 60000"
</script>
Matthew
  • 639
  • 5
  • 11
  • True, i would have done the same in a project scenario, here what i want to understand how function /global scope work in case of nested functions. – Sanjeev Sahoo Aug 04 '15 at 16:21
  • for Parameter case i think chaining itself will take care of it, no need to pass parameters function getScore () { var num1 = 20, num2 = 30; function add() { return name + " scored " + (num1 * num2); } return add(); } – Sanjeev Sahoo Aug 04 '15 at 16:24