Reputation: 316
I feel like I'm fundamentally misunderstanding this works...
All I'm trying to do is figure out how to pass a variable from one function, to another, do something to is and then return the result. That should be pretty simple, right? I've created two really simple functions to experiment with. This is what I have:
function startFunction() {
var variable = 1
adding(variable)
logger.log(variable2)
}
function adding() {
var variable2 = variable + 1
return variable2
}
But the second function (adding) produces a ' "variable" is not defined ' error. So I'm clearly misunderstanding this...any help?
Upvotes: 0
Views: 11050
Reputation: 46794
to summarize comments and other answers (except @Shades one which was simultaneous to mine... well 7 minutes earlier actually ;) ), your code needs to explicitly define every variable in each function (function scope) which means that you can use the same variable names in many functions without any interference (for example one often use var n
in for loops
in different functions, this is obviously and happily not the same n
).
you code should be like this :(read the comments in code)
function startFunction() {
var variable = 1;
var variable2 = adding(variable); // variable is the function parameter
Logger.log(variable2); // Capital matters
}
function adding(v) { // using v as parameter
var variable2 = v + 1 ; // v has the value of variable in startFunction
return variable2;
}
Upvotes: 3
Reputation: 8598
you should end each command with a semicolon ";" and "logger.log" should be "Logger.log" everything is case sensitive in javascript.
try var variable2 = adding(variable);
the use of var creates a local variable that is in a particular scope as mentioned by techowch
variable is in the scope of startFunction and its value is passed to adding function. variable2 is only in the scope of function adding where the value of 1 is added to the value of variable. you return the value of variable2 but there is no variable to receive that value. You can see the value returned by using Logger.log(adding(variable)); but it would not be available for use in startFunction.
Upvotes: 0