Ad

Unexpected Behavior From Prompt Js

- 1 answer

I'm trying to learn javascript, and as part of that exercise, I decided to attempt to create a blackjack simulator to increase my accumen and skills.

Below is an isolated block from the program. I'm using prompt instead of an html interface for simplicity.

function askAboutAce(){
    var nResponse = 0;
    var response = 0;
    response = prompt("Would you like to use the ace as a 1 or 11?");
    if(response === "1" || response === "11"){
        nResponse = Number(response);
        return nResponse;
    }
    else{
        askAboutAce();
    }
}

var x = 2 + askAboutAce();
console.log(x);

The line var x = 2 + askAboutAce(); is simulating the player first drawing a 2, and then drawing an Ace. The odd behavior occurs when I execute the following: If the prompt asks for what I'd like to do with the ace, and I respond correctly (that is, with a 1 or an 11) then the return value is a number. However, if I respond incorrectly (by entering any other number besides 1 or 11) and then eventually I enter the 1 or 11, the return value is NaN. I find that behavior very odd and hypothesize that it has something to do with the resolution of the stack of actions caused by the use of recursion. Please help me understand the unexpected behavior.

Ad

Answer

Every function in javascipt has a return value. If you dont specify anything it will be undefined by default. In the 'if' condition u return the number which is correct. But in the 'else' condition u call the function again which may return a number but since you are not returning the result of the function call, the engine will just return undefined instead. Number(undefined) is NaN. Using the '+' operator with undefined will try to coerce it into a number. There are more rules regarding implicit coercion.

Use return askAboutAce(); in the else condition.

Ad
source: stackoverflow.com
Ad