While loops in javascript are used to execute a block of code repeatedly. It is used when you are uncertain about the number of times the loop needs to be executed.
Example 1: You want to check if the number 10 exists in an array or not and the size of array is really big. Instead of looping all the way to end using for loop we can use while loop.
const arr = [2,3,5,2,2,5,10,12,33]
var i = 0;
while(arr[i]!=10)
{
console.log("10 is present in the array");
i++;
}
In the above example I have used small number of arrays but imagine if the array has 10000+ lines. In that case while loop will be better alternatives.
Example 2: When you are playing video games, let’s take an example of an angry bird. We will use the while loop and use the condition until the bird doesn’t touch the pillars. Keep running the game.
let var = "Bird not touching wall"
while("Bird not touching wall")
{
console.log("Keep playing the game");
}
console.log("Bird touch the pillar exit the game");
Example 3: While loop is used in e-commerce websites. When you will build an e-commerce website. You have to put a condition where the user can buy the product until the stock is empty.