user1863593
user1863593

Reputation: 199

Javascript - variable scope

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();

Upvotes: 1

Views: 80

Answers (2)

Software Engineer
Software Engineer

Reputation: 16110

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.

Upvotes: 3

Lotus
Lotus

Reputation: 2656

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!

Upvotes: 0

Related Questions