function getRent(rent){
var rent = 666;
return rent;
}
function show(){
getRent();
alert(rent);
}
Why is this not working? It comes out as rent
undefined?
function getRent(rent){
var rent = 666;
return rent;
}
function show(){
getRent();
alert(rent);
}
Why is this not working? It comes out as rent
undefined?
There are multiple things wrong with this code.
For one you are redefining the rent variable by using the var keyword in your getRent function.
Secondly when you call getRent you are not assigning its return value to anything and you are effectively asking the console to display an undefined variable.
What you want is
function getRent(){
var rent = 666;
return rent;
}
var rent = getRent();
alert(rent);
or perhaps
function getRent(rent){
rent = 666;
return rent;
}
var param = 1; //sample variable to change
var rent = getRent(param);
alert(rent);
You aren't assigning the return value of getRent()
to anything. rent
is only defined in the getRent
function.
var rent = getRent();
alert(rent);
You define rent
in getRent()
and not in show()
. So rent
is not defined in your case.
Try :
function getRent(rent){
var rent = 666;
return rent;
}
function show(){
alert(getRent("params"));
}
You need to store the returned value of getRent().
function getRent(){
var rent = 666;
return rent;
}
function show(){
var theRent = getRent();
alert(theRent);
}
The reason it doesn't work as you expected is because rent
, defined inside getRent
, is not accessible outside of the function. Variables declared inside functions using the var
keyword are only "visible" to other code inside that same function, unless you return the value to be stored in a variable elsewhere.
It may help you to read up on the basics of functions and function parameters in JavaScript. Here is a good article: http://web-design-weekly.com/blog/2013/01/20/introduction-to-functions-in-javascript/