JavaScript Arrays And Loops Tutorial

JavaScript Arrays Loops TutorialWe have mentioned a few times about <select> boxes being an Array. This tutorial will take you through to understanding JavaScript Arrays and Loops so you can begin to apply them in your own projects. In this lesson we will look at

And lastly we will create the Card Game ’21’ using Arrays!

What Is An Array?

An array is a list of items. Normal JavaScript variables hold one single value, even if that value looks like a list.

shopping_list = "I only need milk";
shopping_list_long = "Milk, Bread, Apples, Cheese, Chicken";

Both of those, from the code’s point of view are single values. Now you can split a single value like this shopping_list_long by the comma, but that gets messy. We can deal with that at a later point!

An array is a list of items that JavaScript knows is a list.

Why Use Arrays?

Arrays sit in between using simple values in variables and needing a database. Arrays can function like a temporary database, altough they should never be used to store sensitive or personal information.

They allow you to create data which is temporarily available to the user without storing them in session variables or cookies. They are massively flexible as well. So if you were creating a Virtual Shop game, you could have an array for bakery, fruit, vegetables, meats for example. You could then use another array to store the items in your basket.

While this is not advisable for an e-commerce system (because these values reset if someone navigates away from your page/site) – it shows what could be done using arrays.

How to Start a New Array

To initialise a brand new array we need to declare the new variable using JavaScript’s var function. There are two ways to do this:

<script type="text/javascript">
 var MyArray = new Array('Apples','Bananas','Pineapples','Peaches');
 var MyArray = ['Apples','Bananas','Pineapples','Peaches'];
</script>

Both these methods do the same thing, but the second one is ‘short hand’. If you can cut down your code at all, then you reduce the file size of your scripts, which makes your page and web application run quicker. Feel free to use whichever makes it easier for you to remember at this point can add pretty much as many items into an array as you want. It’s only limited by the memory of the computer running the page/application.

In this example you can see that we have pre-populated our array with some items.

Adding and Removing Items From An Array

Very rarely will you set up an array and leave it as it is. Taking the shopping list principle – putting an item in your basket adds an item to your basket array. Changing your mind about which brand of chocolate bars would mean removing an item from your basket array then adding the replacement in instead. And if you forget your money once you get to the checkout, you might have to put all your items back on the shelves!

Thankfully adding and removing items is fairly straight forward.

Adding an Item to an Array

To add new item onto the end of an Array you can do this via YourArrayName.push('New Item') function:

var typesOfFruit = ['Apple','Orange','Peach','Pear','Pineapple','Bunch of Grapes','Banana'];
typesOfFruit.push('Guava');
// the end result is that the array would contain
// ['Apple','Orange','Peach','Pear','Pineapple','Bunch of Grapes','Banana','Guava']

If you want to add the item onto the start of your array, you instead need to use .unshift('New Item').

Removing Items From An Array

You can remove items from your list in different ways. You can either remove the first or last item – regardless of what that item is. Or you can remove a specific items, which is probably more useful.

  • To remove the last item from your array simply use YourArrayName.pop()
  • To remove the first item from your array use YourArrayName.shift()

Removing a Specific Item From An Array

Before going into the detail, there is an important principle for you to understand – that of indexation. Each item in an array is also silently given a number, known as it’s index. However, you must remember that the first item in your array is actually index number zero. Read that again!

To be able to remove an item from your array, you have to know – or be able to calculate, the index number. Automatically calculating this is far easier than remembering which number each item is! This is especially true if you’re dynamically adding and removing items from your array.

Obtaining the Index Number of an Item

To find the ‘index number’ of an item, you use this: YourArrayName.indexOf('Item');. So to take the example from above MyArray.indexOf('Bananas'), yields index 1 – the second item in the list.

Removing the Item

Removing a specific item from an array requires you to use JavaScript’s splice('item you want to remove','how many items to remove') function. Inside the brackets you need to use two variables: the first is the index of the item you want to remove from and the second is the number of items you want to remove including that one. So be careful with this – if you only want to remove that specific item, then the second variable will always be 1.

item_to_remove = MyArray.indexOf('Bananas');
MyArray.splice(item_to_remove,1);

How Many Items Are In My Array?

Although you might know how many items you are starting with, you are unlikely to always know how many continue to be in it. Adding and removing items can mean that number is in flux. You can ascertain how many items are in your array with items_in_array = MyArray.length.

Looping Through Your Array

It’s unlikely you will have an array that you don’t want to know the contents of! For that reason you will want to output your array. This is done through what is called, a loop. It’s like reading your shopping list outloud.

Ahead of us building our JavaScript game, let’s consider a deck of cards. They have been shuffled and the dealer starts dealing cards to you. Each card you receive goes into your ‘hand’ – an array of cards – an array we will call CardsDealt. Let’s loop through them and output them to an element on the page with the ID of cardsDrawn:

list_items = '';
 for(var card of CardsDealt){
  list_items+='<li>' + card + '</li>';
}
document.getElementById('cardsDrawn').innerHTML = '<ul>'+list_items+'</ul>';
  • We set up a variable called list_items to store our unordered bullet point list.
  • You need a temporary variable card to ‘store’ the next card that is found.
  • The for loop means it will only continue looking for cards while there are some that have not yet been found.
  • With each item we add to list_items. This short hand of list_items += '<li>New Item</li>' is the same as saying list_items = list_items + '<li>New Item</li>'
  • When all items have been found, we will create the unordered list and output to the page via innerHTML

Applying JavaScript Arrays: Building Card Game ’21’

Let’s now crack on and pull all of this into a JavaScript card game. To make it simpler, I have not used card images in this exercise, but will be releasing a web version of this game. This could be easily extended to make you play against the computer – but one thing at a time!

Setting Up the HTML

Set up your HTML page however you want to. Then somewhere in your <body> section, we need to have a few areas with relevant ID attributes to allow our JavaScript to output certain things during the game:

<h2>Play '21' With JavaScript</h2>
<hr>
<p><strong>Game Status: </strong><span id="gameStatus"></span></p>
<hr>
 <p id="scores"></p>
<hr>
<p id="cardsDrawn">
 <em>Your cards drawn will appear here.</em>
</p>
<input type="button" value="Hit Me" onClick="twenty1('Hit Me');"> <input type="button" value="Stick" onClick="stick();">
<script type="text/javascript">
 twenty1('Shuffle');
</script>

Additional things to note here are:

  • We have triggered a new JavaScript function twenty1(). Inside that is an ‘instruction’ (Shuffle) which will be passed into a JavaScript variable in that function.
  • We set up a ‘Hit Me’ button to send that intruction to our function. ‘Hit Me’ is an informal term in card games to mean ‘Deal me a card’
  • You’ll use a separate button to trigger a function called stick(). This means you don’t want any more cards to be dealt and you want to finalise your score for that round.

Set Up Blank Functions

To make sure that our buttons don’t trigger an error, we need to set them up.

<script type="text/javascript">
 function twenty1(action){
 }
 function stick(){
 }
</script>

Note: The new thing for you here is the use of action within the declaration of twenty1(). That word can be anything (so long it’s not already a function in JavaScript). That is a variable. That means twenty1('Shuffle'); assigns the value of ‘Shuffle’ to the variable ‘action.


Set Global Variables

A global variable is one which any function in your page can access. So in this case we want our stick(); function to be able to reset the current_score. To define a global variable, you need to set it outside of a function (but still inside your <script> </script> tags).

For clarity and to ensure they already exist, I have also set up a blank CardsDealt[] array. And as we want the high_score to be retained no matter how many times we play this is set here as well.

‘Shuffle the Cards’

This function will not do a true shuffle. Although you could have one array listing all the cards and then give them a random order, I wanted to show a few arrays in action. What our action="shuffle" does is make sure that

  • All the cards are back in the deck (as each game will remove cards from it).
  • We reset the current_score variable to zero.
  • All ‘output’ IDs specified in our HTML are reset.
  • The CardsDealt[] array is empty (as no cards have been dealt at the start of the game).
  • You will see each suit array has a ‘DealAgain’ option. Although not 100% necessary, a Math.random() can return zero. As there is no ‘Zero Value’ card in our deck (I have omitted The Joker) I simply want to generate a new random number if a zero is rolled.

The next lesson will take you in more detail with the if(), else if(), else statements. But for now just know that we are running twenty1() and then deciding what to do based on the action variable.

Hit Me – First Step

If the action is ‘Hit Me’, we want to deal a card out of the deck.

else if(action=='Hit Me'){
 document.getElementById('gameStatus').innerHTML = "Game In Progress!";
 if(current_score > 21){
   alert('You have scored higher than 21. Click OK to re-shuffle the deck and start over.');
   twenty1('Shuffle');
  }
  else{
   // choose a random stack
   suit_chosen = Suits[Math.floor(Math.random()*4)];
   if(suit_chosen=="Clubs"){
    items_left_in_suit = Clubs.length;
   }
   else if(suit_chosen=="Hearts"){
    items_left_in_suit = Hearts.length;
   }
   else if(suit_chosen=="Spades"){
    items_left_in_suit = Spades.length;
   }
   else if(suit_chosen=="Diamonds"){
    items_left_in_suit = Spades.length;
   }
   else{
    document.getElementById('gameStatus').innerHTML ='Invalid Suit Chosen - We Will Re-deal!';
    twenty1('Hit Me');
  }
}

The if(current_score > 21) rule just checks that we are not trying to deal a card if the player has scored more than 21. If they have, instead of dealing a card, we will reshuffle the pack. The rest of this stage means this:

  • suit_chosen = Suits[Math.floor(Math.random()*4)]; – Pick a random suit from the Suits[] array and put that into the suit_chosen variable.
  • We need to make sure that we don’t generate a random number which is not in our array of cards in a suit. Using ArrayName.length means we know how much to multiply Math.random() by.
  • Just to make our game solid and to try to catch any random errors, if an invalid suit is chosen we re-trigger twenty1('Hit Me') to pick a different card.
  • Then, depending on which suit is chosen, pick a random card from that suit (out of the cards still available).

Hit Me – Stage 2

Still within your if(action=="Hit Me"){ } code block, we need to do the next round of checks. Although this code snippet is long, each suit is dealt with in the same way.

if(items_left_in_suit==0){
 twenty1('Hit Me'); // try again - this should not end in a loop unless the player deals all cards, which should be prevented by current_score > 21
}
else{
 if(suit_chosen=="Clubs"){
  card_drawn = Clubs[Math.floor(Math.random()*items_left_in_suit)];
  if(card_drawn=="DealAgain"){
   twenty1('Hit Me');
   return;
  }
  // remove card from deck
  card_number = Clubs.indexOf(card_drawn);
  Clubs.splice(card_number,1);
 }
 else if(suit_chosen=="Hearts"){
  card_drawn = Hearts[Math.floor(Math.random()*items_left_in_suit)];
  if(card_drawn=="DealAgain"){
   twenty1('Hit Me');
   return;
  }
  // remove card from deck
  card_number = Hearts.indexOf(card_drawn);
   Hearts.splice(card_number,1);
 }
 else if(suit_chosen=="Spades"){
  card_drawn = Spades[Math.floor(Math.random()*items_left_in_suit)];
  if(card_drawn=="DealAgain"){
   twenty1('Hit Me');
   return;
  }
  // remove card from deck
  card_number = Spades.indexOf(card_drawn);
  Spades.splice(card_number,1);
 }
 else if(suit_chosen=="Diamonds"){
  card_drawn = Diamonds[Math.floor(Math.random()*items_left_in_suit)];
  if(card_drawn=="DealAgain"){
   twenty1('Hit Me');
   return;
  }
  // remove card from deck
  card_number = Diamonds.indexOf(card_drawn);
  Diamonds.splice(card_number,1);
 }
 else{
  document.getElementById('gameStatus').innerHTML = 'Invalid Suit Chosen - We Will Re-deal!';
  twenty1('Hit Me');
 }
}

So what are we doing here?

  • card_drawn = Clubs[Math.floor(Math.random()*items_left_in_suit)]; – we are generating a random number based on items_left_in_suit, from earlier. Then we want to pick a random card from that suit, from those not yet selected.
  • if(card_drawn=="DealAgain"){ } – remember we have a ‘DealAgain’ item in each of our Suit arrays? If this is chosen, then we just force the script to re-deal.
  • return; – instead of letting our program continue on, if ‘DealAgain’ is selected, then return; stops the function from running when it goes back to re-deal.
  • card_number = Clubs.indexOf(card_drawn); – to know which card to remove from that suit, we need its number. This is how we get it!
  • Diamonds.splice(card_number,1); – as per our tutorial here, let’s remove that item from the array. This prevents that card from being drawn again (because it shouldn’t be in our deck any more).

Calculating the Current Score

Based on the card chosen, we want to update the score. As our Suit arrays contain String (word) values, we need to assign them a numerical value (Ace = 14, King = 13, Queen = 12, Jack = 11). For other cards drawn we want to just parseInt() the numerical_value of card_chosen (as they are string values in the array):

// calculate score
if(card_drawn=="Ace"){
 card_value = 14;
 current_score+=card_value;
}
else if (card_drawn=="King"){
 card_value = 13;
 current_score+=card_value;
}
else if (card_drawn=="Queen"){
 card_value = 12;
 current_score+=card_value;
}
else if (card_drawn=="Jack"){
 card_value = 11;
 current_score+=card_value;
}
else{
 card_value = parseInt(card_drawn);
 current_score += card_value;
}

Note here the shorthand current_score += card_value;. This is the same as writing current_score = current_score + card_value;. You can write either, but we always want our scripts to run as fast as possible.

Updating The Game’s Data

Next we want to ensure that the CardsDealt[] array is up to date. This array is here as a readable format to tell the player what cards they have. We will then create a for() loop to output a bullet list of those cards on the page:

// update cards dealt
CardsDealt.push(card_drawn + ' of ' + suit_chosen + ' (' + card_value + ')');
// output cards drawn
list_items = '';
for(var card of CardsDealt){
 list_items+='<li>' + card + '</li>';
}
document.getElementById('cardsDrawn').innerHTML = '<ul>'+list_items+'</ul>';

We first create an empty variable list_items = '';, then add to that with the list items.

Nearly There: Need to check the Score and High Score!

Finally for our action=='Hit Me' section we need to check the new score and see if that’s a new High Score. In the game of 21, your High Score does not count unless you either reach 21 or ‘stick’ at a lower score. If the score is 21, then let’s congratulate the user and re-shuffle. If they have exceeded 21 then it’s “game over”, their high score remains unchanged, and we re-shuffle.

However, if the user’s score is under 21, we just need to update the on-page information:

// check score against high score
if(current_score>21){
 document.getElementById('gameStatus').innerHTML = 'Game Over! Score: '+current_score;
 alert('You have exceeded 21! Press OK to try again!');
 twenty1('Shuffle');
}
else if (current_score==21){
 high_score = 21;
 document.getElementById('gameStatus').innerHTML = 'You have scored <strong>21</strong>!';
 alert('You reached 21! Congratulations! Press OK to Play again!');
 twenty1('Shuffle');
}
else{
 // output current score and high score
  document.getElementById('scores').innerHTML = '<strong>HIGH SCORE:</strong> ' + high_score + '<br><strong>Current Score:</strong> ' + current_score;
}

Allowing a User to Stick

‘Sticking’ in the game of 21 means that the player does not want to be dealt any more cards for this round. In this case we need to check if their current score is a new high score or not. If it is, then we want to update the high_score variable. In both cases, a new game will start:

function stick(){
 // transfer current score to high score if it's higher than the high score
 if(current_score>high_score){
  high_score = current_score;
  alert('This is a new High Score! Press OK to Play Again!');
 }
 else{
  alert('Well done for sticking before you went over 21! Press OK to Play Again!');
 }
 twenty1('Shuffle');
}

And We Are Done!

Now you should have a working JavaScript Game of ’21’! You can Download the full source code here. I have also included another simple arrays function for you to pick apart.

What you can achieve with JavaScript Arrays is only limited by your imagination. Why not try to extend this one-player version to make a game against the computer? To keep it simple force the computer to ‘Stick’ if their score is over a certain number – e.g. 17 or 18. If you feel adventurous you could put another layer to give the computer a probability of picking another card so that it is ‘flawed’ in its thinking!

Well done and thank you for enjoying our JavaScript Tutorials!

Recent JavaScript Tutorials

Spread the Word

Share This On Facebook Share This On Twitter Share This On Linkedin Share This On Google Plus Share This On Pinterest Share This On Mail