2

When the 'hypotenuse' function is called the value of 'x' changes from 1. Fix it so that 'x' is still 1 in the gobal scope.

  var x = 1;
  var y = 1;

  function hypotenuse(a , b) {
    var cSquared = a * a + b * b;
    x = Math.sqrt(cSquared);
    return x;
  }

  hypotenuse(x, y);
Bernardo Baalen
  • 119
  • 1
  • 3
  • 12

2 Answers2

3

All you need to do to make this happen is redeclare the x variable using var within the function. This is will declare the x variable within the scope of the function, leaving the original, globally scoped x variable untouched:

  var x = 1;
  var y = 1;

  function hypotenuse(a , b) {
    var cSquared = a * a + b * b,
        x = Math.sqrt(cSquared);
    return x;
  }

  hypotenuse(x, y);

Or, using the code style which you originally adopted (splitting out var declarations):

  var x = 1;
  var y = 1;

  function hypotenuse(a , b) {
    var cSquared = a * a + b * b;
    var x = Math.sqrt(cSquared);
    return x;
  }

  hypotenuse(x, y);

For more detailed info on what is happening here, read up on javascript scope

Josh Davenport
  • 5,308
  • 2
  • 25
  • 40
  • @BernardoBaalen, replaced `;` with `,` in line `var cSquared` – Satpal Nov 10 '13 at 14:41
  • Yeah, that would do the same thing. The only difference is the first code block in the answer uses var twice. See [Declaring Multiple Variables in JavaScript](http://stackoverflow.com/questions/694102/declaring-multiple-variables-in-javascript) – Josh Davenport Nov 10 '13 at 14:44
  • That is not a very good article on scope in general. It is targeted to one very specific scope issue that people often run into (and an examination of how a number of libraries handle normalizing it for you). – Etan Reisner Nov 10 '13 at 14:45
  • @EtanReisner Yeah that's fair enough. Could you recommend a better one if you know of one? – Josh Davenport Nov 10 '13 at 14:45
1

Try this:

  var x = 1;
  var y = 1;

  function hypotenuse(a, b) {
    var cSquared = a * a + b * b;
    var x = Math.sqrt(cSquared);
    return x;
  }

  //console.log(hypotenuse(x, y));
  //console.log('x = ' + x);
lukpaw
  • 1,473
  • 2
  • 25
  • 31