๐ Scenario: You are working on a simple shopping list app. You need to store the list of items and then access specific items by their position in the list.
๐ฏ Goal: Learn how to create an array and access its elements by index in JavaScript.
๐ What You'll Learn
Create an array with exact items
Create a variable to hold the index to access
Access the array element using the index variable
Print the accessed element
๐ก Why This Matters
๐ Real World
Arrays are used everywhere to store lists of things like shopping items, tasks, or names. Accessing elements by position helps you get or change specific items.
๐ผ Career
Knowing how to work with arrays and access their elements is a basic skill for any programming job, especially in web development and data handling.
Progress0 / 4 steps
1
Create the shopping list array
Create an array called shoppingList with these exact items in order: "milk", "bread", "eggs", "butter", "cheese".
Javascript
Hint
Use square brackets [] to create an array and separate items with commas.
2
Create an index variable
Create a variable called index and set it to 2 to represent the position of the item you want to access in the shoppingList array.
Javascript
Hint
Use const to create a variable and assign the number 2 to it.
3
Access the array element using the index
Create a variable called item and set it to the element in shoppingList at position index.
Javascript
Hint
Use square brackets with the variable index to get the element from the array.
4
Print the accessed item
Write a console.log statement to print the value of the variable item.
Javascript
Hint
Use console.log(item); to show the item in the console.
Practice
(1/5)
1. What is the index of the first element in a JavaScript array?
easy
A. -1
B. 1
C. 0
D. Depends on the array length
Solution
Step 1: Understand array indexing
JavaScript arrays start counting elements from 0, not 1.
Step 2: Identify the first element's index
The first element is always at index 0.
Final Answer:
0 -> Option C
Quick Check:
First element index = 0 [OK]
Hint: Remember arrays start at zero, not one [OK]
Common Mistakes:
Thinking first element index is 1
Confusing negative indexes
Assuming index depends on array length
2. Which of the following is the correct syntax to access the third element of an array named colors?
easy
A. colors{2}
B. colors[2]
C. colors[3]
D. colors(3)
Solution
Step 1: Recall array access syntax
JavaScript arrays use square brackets with zero-based index to access elements.
Step 2: Calculate index for third element
The third element is at index 2 (0,1,2).
Final Answer:
colors[2] -> Option B
Quick Check:
Third element index = 2 [OK]
Hint: Use square brackets and zero-based index [OK]