1

I am going through the heads first js book and encountered a problem.

On the Console it comes out as 7 still when it should be 8? This is in the book so I'm guessing I'm just missing something basic here.

var age = 7;

function addOne(x) {
  x = x + 1;
}

addOne(age);
console.log(age);
mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • 7 is the correct answer... The book is wrong. Numbers are not passed by reference,. If you had age as part of an object literal it would work, as the object is passed by reference. – Keith Dec 01 '17 at 10:33
  • There are two examples, the other goes: – user2293838 Dec 01 '17 at 10:34
  • 1
    When you call `addOne`, `x` gets the same value as `age`, and that’s where their relationship ends. From there, you have two variables, `x = 7` and `age = 7`, then you set `x` to `8`, then the function returns and `x` stops existing. `age` stayed the same the whole time. – Ry- Dec 01 '17 at 10:35
  • Ah thanks Keith, I think I got a bit ahead of myself here. It probably explains this more clear later on in the book. It made sense to me returning that value but I see now that it was not the case. – user2293838 Dec 01 '17 at 10:37
  • I see, i just console.logged within the function of x and it came out 8. Thank you – user2293838 Dec 01 '17 at 10:38

1 Answers1

0

Simply explained: You don't do anything with age. In your function you add one to 7 which is stored as 8 into x and after the function is processed you print out age which is still 7.

To answer your question: Returning the param x would let you return 8. So

   var age = 7;

   function addOne(x) {
    x = x + 1;
    return x;
   }
   console.log(addOne(age));`

should work for you.

sho
  • 44
  • 4