1. Looping control flow allows us to go back to some point in the program and repeat a snippet of code until an exit condition is met. I actually used this in my first program where i solved “multiples of three and five” in project euler.
var number = 10
var result = 0;
var count = 0;
var sum = 0;
for (let count = 1; count <= number; count = count + 1) {
if (count % 3 == 0 || count % 5 == 0) {
if (count < number) {
var result = + count
var sum = sum + result
}
}
}
(I copy pasted my code here, its supposed to be properly indented but it wouldn’t work)
So basically, i use the for keyword to continiously add 1 to “count” as long as count is less then or equal to the number that you give to the program. It then proceeds to test if the value that count has is evenly divisible by 3 or 5 with the modulus operator, if this gets converted to boolean true, the value is then tested if it is less than number given to the program in the beginning. If this also is true, the value held by “count” is then stored in the variable “result”. Then “result” is then added to variable “sum”. This behavior loops until all numbers from 1 up until the number you specify have been tested. Once the entire program has run, “The sum of all the multiples of three and five” between 0 and the number the user has given to the program is now stored in the variable “sum”.
I initially had console.log(sum) at the end of the program but i decided to try to integrate the code in a html file and to try to make it into a fully interactive webpage but i haven’t figured out how to do that yet…
2. I think i described “what loops do” in my answer to the first question. But i would say it repeats a block of code until an exit condition is met.
3. Using the while-function creates a loop that runs a statement that follows it long as the expression that immediately follows the “while”-keyword gets converted to true.
let number = 0;
while (number <= 12) {
console.log(number);
number = number + 2;
}
// → 0
// → 2
// … etcetera
The do-loop on the other hand, always runs its code block at least once, and only starts testing whether it should stop after that first execution.
let yourName;
do {
yourName = prompt(“Who are you?”);
} while (!yourName);
console.log(yourName);
This do loop forces the user to enter a name and will ask again and again until the user has provided something that is not an empty string.
Both examples in this answer is copy-pasted from eloquent javascript.
4. Indentation is adding spaces in a way that makes a program stand out visually in a way that corresponds to the shape of the code blocks inside it. This is to make life easier for the programmer(s) working on the code, because otherwise it can be hard to clearly see where one block of code ends and another begins, as well as where code blocks inside of other code blocks begin and ends.