0

I am trying to create a JavaScript version of an old timey dice game named PIG. It involves rolling dice and keeping track of the sum of each roll. I need to be able to save each roll within a function and then be able to call said function to return the current roll score.


This is the method that takes the amount of the current roll and stores it into the variable total, subsequently returning the current total variable.

  function rollTotal(amount) {
  return amount;
  }

I first call the function and insert the score of the dice roll into the amount parameter...

var dieOne = 1;
var dieTwo = 2;
rollTotal(dieOne + dieTwo);

Then I call the function to return the current score like this...

rollTotal()

and am getting this...

undefined

Is there a way to set a default parameter to return the current score if a parameter is not entered when called?

3
  • amount = amount == null ? defaultValue : amount Commented Sep 6, 2015 at 0:32
  • 2
    This doesn't make sense. rollTotal doesn't update any variable. It's just an identity function, so rollTotal() returns undefined instead of NaN. Commented Sep 6, 2015 at 0:37
  • @Oriol Thanks for the heads up! That is indeed what I was getting, I just posted a typo. I corrected my error. Commented Sep 6, 2015 at 19:16

3 Answers 3

1

When you call a function and don't supply a parameter, then the parameter is bound to undefined within the function. So you can do something like this:

var currentAmount = undefined; // or perhaps 0?
function rollTotal(amount) {
    if (typeof(amount) === 'undefined') {
        return currentAmount;
    } else {
        currentAmount = amount;
        return amount;
    }
}

You can do this more elegantly (and more safely) using a closure:

var rollTotal = (function() {
    var currentAmount = undefined;
    return function(amount) {
        if (typeof(amount) === 'undefined') {
            return currentAmount;
        } else {
            currentAmount = amount;
            return amount;
        }
    };
}());

You might also want to do a more robust test of the argument and treat any non-number as undefined. You can do this with the following test:

!isNaN(parseFloat(amount)) && isFinite(amount)

instead of testing specifically for undefined.

EDIT: As @Paul S. points out, the best test as to whether an argument was passed is arguments.length === 0.

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

4 Comments

Would the downvoters care to explain what's wrong here? Are you reading something in OP's question that I'm missing?
A different test you could do is arguments.length === 0, otherwise the IIFE version of this is basically what I would've written
@PaulS. - Yes, testing arguments.length is probably the right way to go.
@TedHopp - Thanks! This will work just fine. I forgot about this option. You get the answer.
1

Why use a function? The = operator works just fine.

// initial setup
var rollTotal;

// set in the middle of an expression
"You just rolled " + (rollTotal = dieOne + dieTwo) + "!";

// recalling later in an expression
"Last time you rolled " + rollTotal + ", what will you get this time?";

Comments

0

A popular way to do this is with an instance of a class.

That is:

function Dice() {
    var amount;

    this.rollTotal = function(_amount) {
        // if an argument is supplied, assign it to the internal amount
        if (typeof _amount !== "number") {
            amount = _amount;
        }
        return amount;
    };
}

Example usage:

var dice = new Dice();
dice.rollTotal(3);
console.log(dice.rollTotal());

1 Comment

Would the recent downvoter care to explain their reasoning?

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.