Traversing an array means visiting its elements one by one. It's the single most common thing you'll do with an array, and there are only a handful of shapes a traversal can take. Learn them once and you'll recognise them in every solution.
The classic loop. Use it when you need the position as well as the value — to compare neighbours, to write to another array, or to report where something is.
for (let i = 0; i < nums.length; i++) { console.log(i, nums[i]);}Notice the condition is i < length, not i <= length. The last valid index is length - 1, and <= would step one past it — the most common array bug there is.
When you only need the values — summing, counting, finding the max — the "for each" loop is shorter and leaves no index to get wrong.
let total = 0;for (const x of nums) total += x;Start at the last index and count down to 0. Useful when later elements must be handled first — filling an array from the back, as in Merge sorted arrays in place, or building "everything to my right" information.
for (let i = nums.length - 1; i >= 0; i--) { console.log(nums[i]);}In C++, nums.size() is unsigned. Counting down with an unsigned index never goes below zero — it wraps around to a huge number and the loop never ends. Cast to int first, as above.
Put one index at each end and move them toward each other. This is the heart of the two pointer technique: reversing, checking palindromes, and finding pairs in sorted arrays all use it.
let left = 0, right = nums.length - 1;while (left < right) { // look at nums[left] and nums[right] together left++; right--;}Two nested loops, with the inner one starting just after the outer one, visit every pair (i, j) with i < j exactly once. That's how most brute force solutions look — and why they cost O(n²).
for (let i = 0; i < nums.length; i++) { for (let j = i + 1; j < nums.length; j++) { // every pair nums[i], nums[j] once }}Here is the two-ends traversal reversing an array in place. Step through it and watch the pointers close in; try an odd length and an even length.
Change the input, press Run, then step through the code one move at a time.