Manipulating Array Elements Inside a For Loop in JavaScript


Suppose you have an array nums and your task is to increment every number in that array by one.

The first idea that might come to your mind is to write a for loop like this:

let nums = [1, 2, 3];

for (let num of nums) {
  num++;
}
  
console.log(nums);

but when you run this code, you'll be surprised to see that the output is:

[1, 2, 3]

No element in nums changed its value. How is this possible since we clearly do num++ for every num in nums?


Let's talk about copies:

Take a look at this code:

let number = 100;

let number_copy = number;

number_copy++;

console.log(number_copy); // Output: 101
console.log(number); // Output: 100

Although we wrote let number_copy = number;, this doesn't mean that number and number_copy are one and the same.

number_copy is a completely different entity (stored at a different memory address) than number.

What we did is initialize this new number_copy entity with the value of number. That's why we say the number_copy is a copy of number.

And so number_copy++ will only increment number_copy and won't have any effect on number.


The loop variable is just a copy:

This is what also happens with a for loop.

Whenever you write a for loop, the loop variable (in our case num) is just a copy of the current item of the array, not the item itself.

This code

let nums = [1, 2, 3];

for (let num of nums) {
  num++;
}

works exactly like this code:

let nums = [1, 2, 3];

let num = nums[0];
num++;

num = nums[1];
num++;

num = nums[2];
num++;

Notice that only the variable num is being manipulated, which has nothing to do with the actual entries of the array nums.

You'll see this better if we also print the value of num on each iteration.

let nums = [1, 2, 3];

for (let num of nums) {
  num++;
  console.log(num);
}

console.log(nums);

The output of this code is:

2
3
4
[1, 2, 3]

Looping over the indices:

In order to manipulate the entries of some array we have to loop over the items' indices:

let nums = [1, 2, 3];

for (let index = 0; index < nums.length; index++) {
  nums[index]++;
}
  
console.log(nums); // Output: [2, 3, 4]

This code works exactly like this one:

let nums = [1, 2, 3];

let index = 0;
nums[index]++;

index++;
nums[index]++;

index++;
nums[index]++;

console.log(nums);

In this way we directly manipulate the actual entries of the list (nums[0], nums[1], etc.)

Assignment:

Fix our code such that it correctly increments (adds one to) the even numbers of nums and decrements (subtracts one from) the odd ones.

Introduction

In this lesson, we will explore how to manipulate array elements inside a for loop in JavaScript. This is a fundamental concept in programming that is widely used in various scenarios, such as data processing, algorithm implementation, and more. Understanding how to correctly manipulate array elements is crucial for writing efficient and bug-free code.

Understanding the Basics

Before diving into the solution, let's understand the basic concepts. When you iterate over an array using a for loop, the loop variable is a copy of the array element, not the element itself. This means that any changes made to the loop variable do not affect the original array.

For example:

let number = 100;
let number_copy = number;
number_copy++;
console.log(number_copy); // Output: 101
console.log(number); // Output: 100

Here, number_copy is a copy of number, and incrementing number_copy does not change number.

Main Concepts

To manipulate the actual elements of an array, you need to loop over the indices of the array. This allows you to directly access and modify the elements.

For example:

let nums = [1, 2, 3];
for (let index = 0; index < nums.length; index++) {
  nums[index]++;
}
console.log(nums); // Output: [2, 3, 4]

In this code, we loop over the indices of the array and increment each element by one.

Examples and Use Cases

Let's look at a specific example where we need to increment even numbers and decrement odd numbers in an array:

let nums = [1, 2, 3, 4, 5];
for (let index = 0; index < nums.length; index++) {
  if (nums[index] % 2 === 0) {
    nums[index]++;
  } else {
    nums[index]--;
  }
}
console.log(nums); // Output: [0, 3, 2, 5, 4]

In this example, we check if each element is even or odd and then increment or decrement accordingly.

Common Pitfalls and Best Practices

One common mistake is to manipulate the loop variable instead of the array element. Always ensure you are modifying the array element directly. Additionally, use meaningful variable names and keep your code clean and readable.

Advanced Techniques

For more advanced manipulation, you can use higher-order functions like map, filter, and reduce. These functions provide a more functional approach to array manipulation.

For example, using map to achieve the same result:

let nums = [1, 2, 3, 4, 5];
nums = nums.map(num => num % 2 === 0 ? num + 1 : num - 1);
console.log(nums); // Output: [0, 3, 2, 5, 4]

Code Implementation

Here is the complete code implementation for the assignment:

let nums = [1, 2, 3, 4, 5];
for (let index = 0; index < nums.length; index++) {
  if (nums[index] % 2 === 0) {
    nums[index]++;
  } else {
    nums[index]--;
  }
}
console.log(nums); // Output: [0, 3, 2, 5, 4]

Debugging and Testing

When debugging, use console.log to print intermediate values and understand the flow of your code. For testing, you can write test cases to verify the correctness of your function.

Example test case:

function testIncrementDecrement() {
  let nums = [1, 2, 3, 4, 5];
  let expected = [0, 3, 2, 5, 4];
  for (let index = 0; index < nums.length; index++) {
    if (nums[index] % 2 === 0) {
      nums[index]++;
    } else {
      nums[index]--;
    }
  }
  console.assert(JSON.stringify(nums) === JSON.stringify(expected), 'Test failed');
}
testIncrementDecrement();

Thinking and Problem-Solving Tips

When approaching problems, break them down into smaller parts and solve each part step-by-step. Practice regularly with coding exercises and projects to improve your problem-solving skills.

Conclusion

In this lesson, we covered how to manipulate array elements inside a for loop in JavaScript. We discussed the importance of understanding copies, looping over indices, and provided examples and best practices. Mastering these concepts is essential for writing efficient and maintainable code.

Additional Resources

For further reading and practice, check out the following resources: