Use a `for` loop, `forEach()`, or `while` loop to iterate an array in XenonCode
Iterating arrays in XenonCode follows standard JavaScript-like syntax. Use a `for` loop for index-based control, `forEach()` for concise iteration, or `while` for conditional traversal. XenonCode supports array methods like `map()`, `filter()`, and `reduce()` for functional programming.
4 Ways to Iterate an Array
1. Classic for Loop
- Best for index-based operations or breaking early.
- Syntax:
for (let i = 0; i < array.length; i++) { console.log(array[i]); }
2. forEach() Method
- Cleaner syntax for simple iteration (no index needed).
- Syntax:
array.forEach((item, index) => { console.log(item); }); - Note: Cannot use
breakorcontinue.
3. while Loop
- Useful for dynamic conditions (e.g., iterating until a value is found).
- Syntax:
let i = 0; while (i < array.length) { console.log(array[i]); i++; }
4. Functional Methods (map, filter, reduce)
map(): Transform each item (returns new array).filter(): Return items matching a condition.reduce(): Aggregate values (e.g., sum, concatenate).- Example:
const doubled = array.map(x => x 2);
Performance Comparison
| Method | Best For | Performance | Can Break Early? |
|---|---|---|---|
for loop |
Index control, large arrays | ⚡ Fastest | ✅ Yes |
forEach() |
Simple iteration | Fast | ❌ No |
while loop |
Dynamic conditions | Fast | ✅ Yes |
map()/filter() |
Transforming data | Moderate (creates new array) | ❌ No |
Key Notes for XenonCode
- XenonCode arrays are zero-indexed (first element at
array[0]). - Avoid modifying arrays during iteration (can cause unexpected behavior).
- Use
array.lengthto get the size dynamically. - For nested arrays, use nested loops (e.g.,
forinsidefor).
Example: Summing Array Values
// Using for loop
let sum = 0;
for (let i = 0; i < numbers.length; i++) {
sum += numbers[i];
}
// Using reduce()
const sum = numbers.reduce((acc, num) => acc + num, 0);