Reputation: 1253
I have looked at many examples but still cant figure how the return statement works.
function One() {
var newVal = 0;
Too();
console.log(newVal);
}
function Too(newVal) {
++newVal;
return(newVal);
}
Shouldn't this print 1 to the console? What I'm really trying to do is to have function Too increase newVal by 1 every time it's called. But I cant even figure out how to get the return statement to work. I should mention I don't want to use global variables. Thanks for any help.
Upvotes: 1
Views: 227
Reputation: 1075925
Shouldn't this print 1 to the console?
No. The newVal
inside Too
is not the newVal
inside One
. They're completely separate.
What I'm really trying to do is to have function Too increase newVal by 1 every time it's called.
It can't, JavaScript doesn't have any mechanism for passing variables by reference like some other languages do (C#'s ref
and out
arguments, for instance). The closest you can come is to pass in a reference to an object and modify the object's state (which is really quite different and I won't go into it here as it would confuse things :-) ).
None of which has anything to do with the return
statement.
The simplest way to do what you were describing is this:
function One() {
var newVal = 0;
newVal = Too(newVal);
console.log(newVal);
}
function Too(arg) {
++arg;
return arg;
}
Here's what happens when we call One
:
newVal
is created.0
.Too
as an argument. This has no link back to the newVal
variable.Too
is called, accepting that value in its arg
argument (arguments in JavaScript are effectively local variables).Too
increments the value in arg
.Too
returns a copy of the value held by arg
as its return value.Too
is assigned to the variable newVal
.console.log
).Upvotes: 4
Reputation: 5438
If a function return a value you need to call that function in your console.log
or capture the returned value.
function One() {
var newVal = 0;
console.log(Too(newVal));
}
function Too(newVal) {
++newVal;
return(newVal);
}
Upvotes: 1
Reputation: 414096
No, it shouldn't. The return
statement establishes what the value of the function invocation will be in the calling environment when control returns there. Since your calling environment doesn't use the return value, there's no net effect.
Here's how you'd get the value back:
newVal = Too(newVal);
If you want to make a function that acts as a counter, such that each time you call it you get a new number back, you can do something like this:
var counter = function(initial) {
var c = initial || 0;
return function() {
return c++;
};
}(0);
What that does is use an anonymous function to set up a persistent environment for another function, which is returned from the outer one when it's (immediately) invoked. The returned function can then be called to return a new value from its private counter (the variable "c"):
var currentCount = counter();
alert(currentCount); // 0, the first time
currentCount = counter();
alert(currentCount); // 1, and so on
Upvotes: 2