Array loop

2 snippets across 2 stacks — Bash & Linux, JavaScript

Also written as iterate array

SHBash & Linux

Arrays

SH · Bash Scripting
syntax
arr=(val1 val2 val3)
${arr[0]}  ${arr[@]}  ${#arr[@]}
example
SERVERS=("web01.prod" "web02.prod" "db01.prod")
echo "First: ${SERVERS[0]}"
echo "All: ${SERVERS[@]}"
echo "Count: ${#SERVERS[@]}"

SERVERS+=("cache01.prod")

for srv in "${SERVERS[@]}"; do
  ssh deploy@"${srv}" 'uptime'
done
output
First: web01.prod
All: web01.prod web02.prod db01.prod
Count: 3

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.

JSJavaScript

for...of Loop

JS · Control Flow
syntax
for (const element of iterable) { ... }
example
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 too
for (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.