Putting it together · Juntando tudo
Putting it together
- Real programs combine variables, loops, functions, arrays and objects.
- A
for...ofloop reads each item of an array directly — no index needed.
Juntando tudo
- Programas reais combinam variáveis, loops, funções, arrays e objetos.
- Um
for...ofloop lê cada item de um array diretamente — nenhum índice necessário.
function total(nums) {
let t = 0;
for (const n of nums) {
t = t + n;
}
return t;
}
console.log(total([4, 8, 6])); // → 18
for...of builds the total · for...of constrói o total
for...of reads each item directly. Watch t add them up, one at a time. · for...of lê cada item diretamente. Observe t somá-los, um de cada vez.
Searching and counting
- Loop through the array, and keep a counter (or a flag) as you go.
Busca e contagem
- Itere pelo array e mantenha um contador (ou uma flag) à medida que avança.
function countAbove(nums, limit) {
let count = 0;
for (const n of nums) {
if (n > limit) {
count++;
}
}
return count;
}
console.log(countAbove([3, 7, 2, 8], 4)); // → 2
Common mistakes
- Build in small steps and use
console.logto check as you go. - Keep the HTML, CSS and JavaScript doing their own jobs.
Erros comuns
- Construa em pequenos passos e use
console.logpara verificar conforme avança. - Mantenha HTML, CSS e JavaScript fazendo seus próprios trabalhos.
Now you try
- Write each function using a loop.
- Press Check answer to test it.
Agora você tenta
- Escreva cada função usando um loop.
- Pressione Check answer para testá-lo.
Write a function total(nums) that returns the sum of every number in the array nums. · Escreva uma função total(nums) que retorne a soma de todos os números na matriz nums.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.
Write a function biggest(nums) that returns the largest value in the array. · Escreva uma função biggest(nums) que retorne o valor maior na matriz.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.
Write a function countAbove(nums, limit) that returns how many numbers are greater than limit. · Escreva uma função countAbove(nums, limit) que retorne quantos números são maiores que limit.
Click Run to see the output here. · Clique em Executar para ver a saída aqui.