JSFiddle - React, Tailwind, and code Playground
by Abdul Ahmad
JavaScript
function add2(num1, num2) {
var total = num1 + num2;
alert(total);
}
add2(5, 6);
add2(10, 60);
var theNumbers = [
4, // 0
7, // 1
1, // 2
3, // 3
6, // 4
10 // 5
];
var theNumbers2 = [
1000,
2000,
5000,
10000
];
// function declaration
// it defines what the function does
// but doesnt actually use it
function addMany(arrayOfNumbers) {
var total = 0;
for(var i = 0; i < arrayOfNumbers.length; i++) {
// ***** loop start
// only runs if condition is true (i < arrayOfNumbers.length)
var numberAtIndex = arrayOfNumbers[i];
total = total + numberAtIndex;
// ***** loop end
}
// next line after loop is finished
alert(total);
}
// called function invocation
// actually runs the function
addMany(theNumbers);
addMany(theNumbers2);
addMany([5, 6, 7, 8, 9]);
/*
first iteration
i = 0
i < 5 is true
get value of array at index i (which is 0)
add it total
increment i (i = 1)
second iteration
i = 1
i < 5 is true
get value of array at index i (which is 1)
add it to tatal
increment i (i = 2)
.....
sixth iteration
i = 5
5 < 5 is false
dont do anything else inside of the loop body
go to next line in function
*/