Putting it together · Poniéndolo en conjunto
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 todo
- Los programas reales combinan variables, bucles, funciones, arrays y objetos.
- Un bucle
for...oflee cada elemento de un array directamente — sin necesidad de un índice.
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 construye el total
for...of reads each item directly. Watch t add them up, one at a time. · for...of lee cada elemento directamente. Observa cómo t los suma, uno a la vez.
Searching and counting
- Loop through the array, and keep a counter (or a flag) as you go.
Búsqueda y conteo
- Recorre el array y mantén un contador (o una bandera) a medida que avanzas.
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.
Errores comunes
- Construye paso a paso y usa
console.logpara verificar a medida que avanzas. - Mantén al HTML, CSS y JavaScript haciendo sus propios trabajos por separado.
Now you try
- Write each function using a loop.
- Press Check answer to test it.
Ahora tú intentarlo
- Escribe cada función usando un bucle.
- Presiona Comprobar respuesta para probarla.
Write a function total(nums) that returns the sum of every number in the array nums. · Escribe una función total(nums) que devuelva la suma de todos los números en el array nums.
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.
Write a function biggest(nums) that returns the largest value in the array. · Escribe una función biggest(nums) que devuelva el valor más grande del array.
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.
Write a function countAbove(nums, limit) that returns how many numbers are greater than limit. · Escribe una función countAbove(nums, limit) que devuelva cuántos números son mayores que limit.
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.