1

I am not seeing the issue here. I am new at JavaScript. I have researched variable scope and this looks correct to me. The issue is the variable, useAge, in the legalAge function is undefined. I have it declared before the function and passing it as a parameter to the function.

"use strict";

function person(){
    alert("person function 1");
    var personName = prompt("Enter a name:", "enter name here");
    var personAge = parseInt(prompt("Enter " +  personName + "'s current age:", "enter age here"));
    var votingStatus = legalAge();
    var statusMessage =  (votingStatus == true) ? "old enough" : "not old enough";
    document.writeln("<b>" + personName + " is " + personAge + " years old " + statusMessage + "</b><br />");
    return personAge;   
}


var useAge = person();
alert("useAge: " + useAge);
alert("outside function");

function legalAge(useAge) {
  alert("legalVoting function 2");
  var canVote = (useAge >= 18) ? true : false;  
  alert("Can Vote: " + canVote);
  alert("age: " + useAge);
  return canVote;       
}

person();
5
  • 1
    You could reduce the canVote line to var canVote = useAge >= 18; Commented Oct 9, 2014 at 20:03
  • Also, the last line is not really needed is it? Commented Oct 9, 2014 at 20:08
  • "and passing it as a parameter to the function." No your a not. Commented Oct 9, 2014 at 20:11
  • You are correct, the last line is not needed. Commented Oct 9, 2014 at 20:12
  • Felix, I was referring to useAge variable. Commented Oct 9, 2014 at 20:13

2 Answers 2

3

The problem is that you haven't passed personAge into the legalAge() function. You need:

var votingStatus = legalAge(personAge);

Otherwise useAge in legalAge() is undefined and you'll get errors using it.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for fixing my typo mate :)
Thank you. I passed "personage" into the legalAge() function. I was looking at it like it was being passed with the useAge variable that is = person().
0

Couple things to note here:

var useAge = person()

The above line will assign the return value from person() to useAge sure enough...

function legalAge(useAge) {
    ....
}

The above function has a parameter called useAge which is local to the function, and must be passed as an argument when calling the function. I.E. legalAge(10). This would be fine and dandy, except...

function person() {
    ....
    var votingStatus = legalAge();
    ....
}

the person() function is defined to call legalAge() with no parameters. In doing so, legalAge executes and does not have a value for its parameter.

Also, the useAge parameter is different from the global useAge variable.

Hope this helps!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.