0

This is my code:

var shuffle = function(x) {
    var deck = [];
    deck.push(x);

    return deck;
};

var Placemat = function() {
    var card1 = deck.shift();
    var card2 = deck.shift();
}

By returning deck in shuffle() like this, can I use it in Placemat()? If not, how can I do it?

dopatraman
  • 13,416
  • 29
  • 90
  • 154

4 Answers4

2

Yes you could. But anytime you call .shuffle() you would overwrite that array, or more precisely, create a new instance. So if you want to keep that reference you could go like

var shuffle = (function() {
    var deck = [];

    return function(x) {
        deck.push(x);

        return deck;
    };
}());

Now .shuffle() closes over the deck by returning another function. So it could look like

var Placemat = function() {
    var myDeck = shuffle(5);

    shuffle(10);
    shuffle(15);

    var card1 = deck.shift();
    var card2 = deck.shift();
}

Even if that is probably not the greatest way to go. But I guess I don't even know what exactly you want to achieve there.

jAndy
  • 231,737
  • 57
  • 305
  • 359
0

You cannot you have to put them in the parameters or outside the function.

var shuffle = function(x) {
    var deck = [];
    deck.push(x);

    return deck;
};

 var Placemat = function(deck) {
    var card1 = deck.shift();
    var card2 = deck.shift();
}

or 

var deck = [];
var Placemat = function() {
    var card1 = deck.shift();
    car card2 = deck.shift();
}
yokoloko
  • 2,820
  • 3
  • 20
  • 27
0

You can use the return value from shuffle in Placemat, but it will always be an array with a single item in it.

If you want to have a variable deck that contains multiple items, deck will need to be declared in an outer scope:

var deck = [];

var shuffle = function(x) {
    deck.push(x);
    return deck;
}

var Placemat = function() {
    var card1 = deck.shift();
    var card2 = deck.shift();
};

This way, both the shuffle function and Placemat are using the same variable deck.

FishBasketGordo
  • 22,904
  • 4
  • 58
  • 91
-1

I found another solution:

var shuffle = function(deck,x) {
    var deck = [];
    deck.push(x);

    return deck;
};

var Placemat = function() {
    var newdeck = shuffle(deck,x)
    var card1 = newdeck.shift();
    var card2 = newdeck.shift();
}

This way I don't have to make deck a global variable. Thanks for the help everyone.

dopatraman
  • 13,416
  • 29
  • 90
  • 154