Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JavaScript - Pass-by-value || Page 92 #9

Open
adityathebe opened this issue Jul 21, 2015 · 2 comments
Open

JavaScript - Pass-by-value || Page 92 #9

adityathebe opened this issue Jul 21, 2015 · 2 comments

Comments

@adityathebe
Copy link

var age = 7;
function addOne (x) {
x = x +1;
}
addOne(age);
document.write(age);

I'm gonna break this down the way I have understood.

So, we have a function called addOne which adds 1 to the value it accepts, right?
And then we call the function with an argument of the value 7. So, now the function adds 1 to 7 and age is 8.
But why is it that when I print out the value of age, it prints out 7 ??

@bethrobson
Copy link
Owner

Hi adityathebe,

That's because JavaScript uses "pass by value". That means the value 7 gets copied into the variable x. You increase the variable x, but that doesn't change the value of age because they are two different variables.

If you want to change the value of age, you'd write it like this:

var age = 7;
function addOne(x) {
    x = x + 1;
    return x;
}
age = addOne(age);
document.write(age);

Here, if we return the value of x (which is now 8), and store that new value in age, then age will be 8. Do you see the difference?

Review page 92 again.

Hope that helps!

@adityathebe
Copy link
Author

Thank you. I'm really loving your book !!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants