While Loop
Part of the Fundamentals section of Coddy's JavaScript journey — lesson 39 of 77.
A while loop is different from the for loop. A for loop allows us to iterate over a specific range, whereas a while loop allows us to keep iterating as long as a certain condition is met.
To use a while loop write:
while (condition) {
code;
}The code will execute only if the condition is true.
There are many use cases where a while loop is more suitable than a for loop — especially when the number of iterations is not known in advance.
For example consider this problem:
Find the smallest power of 2 that is greater than a given number.
To solve it we will use a while loop that will repeatedly multiply the current power of 2 by 2 until it becomes greater than the given number:
let number = 27;
let power_of_two = 1;
while (power_of_two <= number) {
power_of_two *= 2;
}
console.log(power_of_two);Challenge
BeginnerWrite a program that gets one input, float number.
Use a while loop to divide the input by 2 as long as the number is bigger or equal to 3.5.
Print the first number that is smaller than 3.5.
Cheat sheet
A while loop executes code as long as a condition is true:
while (condition) {
code;
}Example - finding the smallest power of 2 greater than a given number:
let number = 27;
let power_of_two = 1;
while (power_of_two <= number) {
power_of_two *= 2;
}
console.log(power_of_two);Try it yourself
let number = parseFloat(inp); // Don't change this line
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Type Coercion7Bill Split Calculator
Welcome MessageCalculating The Tip And Total2Variables
NumbersStringBooleanNaming ConventionsEmpty VariablesRecap - Initialize VariablesConstants3Operators Part 1
Arithmetic OperatorsModulo OperatorArithmetic ShortcutsComparison OperatorsStrict vs Loose EqualityRecap - Simple Math6Basic IO
OutputOutput with VariablesType Conversion - Part 1Type Conversion - Part 2Recap - Till 120Recap - True or False