Note Indices start at 0. Always quote "${arr[@]}" to preserve elements with spaces. ${#arr[@]} gives the length. += appends. unset 'arr[1]' removes an element (but does not reindex). Bash arrays are not available in sh/POSIX shell.
const scores =[88,92,75,100];let sum =0;for(const score of scores){
sum += score;}console.log(`Average: ${sum / scores.length}`);// Works with strings toofor(const char of"hello"){process(char);}
Output
"Average: 88.75"
Note Works on any iterable: arrays, strings, Maps, Sets, generators. Does NOT work on plain objects -- use Object.entries() or for...in for those.
Frequently asked questions
How does Bash & Linux handle array loop?
This task is covered in 2 stacks on this page: Bash & Linux, JavaScript. The "Arrays" snippet in Bash & Linux uses `arr=(val1 val2 val3)`.
Which command does the Bash & Linux example use?
The "Arrays" snippet uses `arr=(val1 val2 val3)`, from the Bash Scripting section of the Bash & Linux cheat sheet.
Which stacks cover "array loop" on this page?
Bash & Linux, JavaScript. Together they hold 2 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "Arrays": Indices start at 0. Always quote "${arr[@]}" to preserve elements with spaces. ${#arr[@]} gives the length. += appends. unset 'arr[1]' removes an element (but does not reindex). Bash arrays are not available in sh/POSIX shell.