Explore 100's Of Free Video Tutorials

Keep Learning, Keep Coding & Keep Sharing

When to use break statement ?

Notes:

When to use break statement ?
We can use break statement for writing efficient codes.

Liner searching without break statement:
In best, worst and average cases executes for loop 5 times.
The best case is when item is at 0 th index
The worst case is when item is at 4 th index.
The average case is when item is between 1 to 5 th index.

Ex:
var numbers = [10,20,30,40,50];
var item= 20;
var found = false;
for(var i=0; i<5; i++)
{
if(numbers[i]==item)
{
found= true;
}
}
document.write(found);

Liner searching with break statement:
In best case executes for loop in single step.
The best case is when item is at 0 th index
In worst case executes for loop 5 times.
The worst case is when item is at 4 th index.
In average case executes from 1 to 5.
The average case is when item is between 1 to 5 th index.

Ex:
var numbers = [10,20,30,40,50];
var item= 20;
var found = false;
for(var i=0; i<5; i++)
{
if(numbers[i]==item)
{
found= true;
break;
}
}
document.write(found);

Interview Questions: