Arrays

What are arrays?

Arrays are a way to store multiple values in a single variable. Instead of creating separate variables for each value, you can group them together in an ordered list.

Benefits of using arrays?

  • Store multiple values with one variable name
  • Access values by their position (index)
  • Easier to loop through related data
  • Keep code organized and scalable
  • Work well with game objects and collections
// Creating and using arrays
const gameObjects = ['player', 'guard', 'npc', 'background'];

// Accessing array elements
console.log(gameObjects[0]); // player
console.log(gameObjects[2]); // npc

// Adding items
gameObjects.push('collectible');

// Getting length
console.log(gameObjects.length); // 5

// Looping through array
for (let i = 0; i < gameObjects.length; i++) {
    console.log(gameObjects[i]);
}

// Using forEach method
gameObjects.forEach(item => {
    console.log("Item: " + item);
});

What does this code do?

  • Creates an array with 4 game object names
  • Accesses individual items using index notation (0 = first item)
  • Uses push() to add a new item to the end
  • Gets the length property to count items
  • Loops through each item with a for loop
  • Uses forEach() method to run code for each item
## Try It Yourself

%%js
// CODE_RUNNER: arrays
const items = ['sword', 'shield', 'potion'];
items.push('bow');
console.log(items.length);
console.log(items[0]);
items.forEach(item => console.log(item));