Search code examples
javascriptglobal-variableslocal-variables

how to calculate sum, multiply, modulus of two global variables and two local variables?


I am quite confused to understand the logic in my question as i"m new to javascript but i tried to write some logic mentioned below but unable to understand what logic to write exactly to get the result. If someone can please help me in rectifying my code and help me understand to get the result.

JS

// Global Variable 
var a = 40;
var b = 70;

function var_ops_5() {
 
  // Local Variable 
  var a = 4;
  var b = 7;
  var c = a + b;
  var d = a * b;
  var e = a % c;
};

Solution

  • Using var is the problem. You can't have var = 40 and then have var a = 4 inside a block because with var, variables declared inside a block can be accessed from outside the block. The var a = 4 inside your function overwrites var = 40. If you change them to let keyword it should work as intended.