1
function getRent(rent){
    var rent = 666;
    return rent;
}
function show(){

getRent();
alert(rent);
}

Why is this not working? It comes out as rent undefined?

Elton Frederik
  • 259
  • 1
  • 3
  • 12
  • Why are you passing in a `rent` parameter to `getRent()`? – Andy Jan 23 '14 at 15:18
  • You should read this post to get a better understanding of scope. http://stackoverflow.com/questions/500431/javascript-variable-scope – Smeegs Jan 23 '14 at 15:23

4 Answers4

3

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);
BenM
  • 4,218
  • 2
  • 31
  • 58
2

You aren't assigning the return value of getRent() to anything. rent is only defined in the getRent function.

var rent = getRent();
alert(rent);
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
1

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"));
}
R3tep
  • 12,512
  • 10
  • 48
  • 75
1

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/

Josh Harrison
  • 5,927
  • 1
  • 30
  • 44