The first type of loop we will learn is called a while loop because it runs while a specified condition is true and stops once that condition is no longer true.const ourArray = [];let i = 0;while (i < 5) { ourArray.push(i); i++;}In the code example above, the while loop will execute 5 times and append the numbers 0 through 4 to ourArray.Let's try getting a while loop to work by pushing values to an array.Add the numbers 5 through 0 (inclusive) in descending order to myArray using a while loop.
Question
The first type of loop we will learn is called a while loop because it runs while a specified condition is true and stops once that condition is no longer true.const ourArray = [];let i = 0;while (i < 5) { ourArray.push(i); i++;}In the code example above, the while loop will execute 5 times and append the numbers 0 through 4 to ourArray.Let's try getting a while loop to work by pushing values to an array.Add the numbers 5 through 0 (inclusive) in descending order to myArray using a while loop.
Solution
Here is how you can use a while loop to add the numbers 5 through 0 (inclusive) in descending order to an array:
let myArray = [];
let i = 5;
while (i >= 0) {
myArray.push(i);
i--;
}
In this code:
- We first declare an empty array
myArray. - We then declare a variable
iand initialize it to 5. - We set up a while loop that will run as long as
iis greater than or equal to 0. - Inside the loop, we use the
pushmethod to add the current value ofito the end ofmyArray. - We then decrement
iby 1. - Once
iis no longer greater than or equal to 0, the loop stops running.
As a result, myArray will end up holding the numbers 5 through 0 in descending order.
Similar Questions
const ourArray = [];for (let i = 0; i < 5; i++) { ourArray.push(i);}ourArray will now have the value [0, 1, 2, 3, 4].Use a for loop to push the values 1 through 5 onto myArray.
What is the output of the following TypeScript code?let arr = [1, 2, 3, 4];for (let i = 0; i < arr.length; i++) { if (i === 2) continue; console.log(arr[i]);}*1 point1 2 3 41 3 41 2 41 2 4 3
What does the forEach() method do in JavaScript arrays?Question 2Answera.Adds elements to the beginning of an arrayb.Removes elements from an arrayc.Iterates over each element of the array and executes a functiond.Sorts the elements in the array
What will be the output of the following TypeScript code?let array = [10, 20, 30];for (let value of array) { console.log(value);}*1 point0 1 210 20 30value[10, 20, 30]
Select the correct answerDescribe a scenario where a do-while loop would be more appropriate than a while loop.Options When you need to ensure the loop body executes at least onceWhen you need to check the condition before the first iterationWhen you need to iterate a known number of timesWhen you're working with arrays
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.