📖 Scenario: You are managing a list of daily temperatures recorded in a week. Sometimes, you need to check the temperature of a specific day or update it if there was a mistake in recording.
🎯 Goal: Learn how to access and update values at specific positions in an array using JavaScript.
📋 What You'll Learn
Create an array with exact temperature values for 7 days
Create a variable to hold the index of the day to update
Update the temperature at the specified index
Print the updated array
💡 Why This Matters
🌍 Real World
Managing daily data like temperatures, sales, or scores often requires accessing and updating specific entries in a list.
💼 Career
Understanding how to access and update array elements is fundamental for software development, data analysis, and many programming tasks.
Progress0 / 4 steps
1
Create the temperature array
Create an array called temperatures with these exact values: 22, 24, 19, 23, 25, 20, 21
DSA Javascript
Hint
Use square brackets [] to create an array and separate values with commas.
2
Set the index to update
Create a variable called dayIndex and set it to 3 to represent the fourth day (index starts at 0)
DSA Javascript
Hint
Remember, array indexes start at 0, so the fourth day is index 3.
3
Update the temperature at the given index
Update the value in temperatures at index dayIndex to 26
DSA Javascript
Hint
Use square brackets with the index to access and assign a new value.
4
Print the updated temperatures array
Print the temperatures array using console.log(temperatures)
DSA Javascript
Hint
Use console.log to display the array in the console.
Practice
(1/5)
1. What does arr[2] return if arr = [10, 20, 30, 40]?
easy
A. 40
B. 20
C. 10
D. 30
Solution
Step 1: Understand array indexing
Arrays start at index 0, so index 2 is the third element.
Step 2: Identify the element at index 2
The element at index 2 in [10, 20, 30, 40] is 30.
Final Answer:
30 -> Option D
Quick Check:
Index 2 element = 30 [OK]
Hint: Remember arrays start at zero index [OK]
Common Mistakes:
Thinking index starts at 1
Confusing element value with index
Using negative index without explanation
2. Which of the following is the correct way to update the 3rd element of array nums to 50?
easy
A. nums[3] = 50;
B. nums(3) = 50;
C. nums[2] = 50;
D. nums{2} = 50;
Solution
Step 1: Recall array indexing syntax
In JavaScript, arrays use square brackets with zero-based index.
Step 2: Identify correct index for 3rd element
The 3rd element is at index 2, so nums[2] = 50; is correct.
Final Answer:
nums[2] = 50; -> Option C
Quick Check:
Use square brackets and zero-based index [OK]
Hint: Use square brackets and zero-based index [OK]