xxxxxxxxxx
// Example 1: Using break in a loop
for (var i = 0; i < 5; i++) {
if (i === 3) {
break; // Exit the loop when i is equal to 3
}
console.log(i);
}
// Output: 0 1 2
// Example 2: Using break in a switch statement
var day = "Monday";
switch (day) {
case "Monday":
case "Tuesday":
case "Wednesday":
case "Thursday":
case "Friday":
console.log("Working day");
break; // Exit the switch statement
case "Saturday":
case "Sunday":
console.log("Weekend day");
break; // Exit the switch statement
default:
console.log("Invalid day");
}
// Output: Working day
xxxxxxxxxx
// program to print the value of i
for (let i = 1; i <= 5; i++) {
// break condition
if (i == 3) {
break;
}
console.log(i);
}
xxxxxxxxxx
//break out of for loop
for (i = 0; i < 10; i++) {
if (i === 3) { break; }
}
xxxxxxxxxx
// The break statement breaks out of a switch or a loop.
let text = "";
for (let i = 0; i < 5; i++) {
if (i == 3) break;
text += i;
}
// output: 012
xxxxxxxxxx
for (let i = 0; i < 10; i++) {
// Some condition to check
if (i === 5) {
break; // Break out of the loop
}
console.log(i);
}
xxxxxxxxxx
async function authenticate(
{ body: { email, password: plainPassword } }: Request, res: Response
): Promise<void> { authenticate: {
const user = await getUserByEmail(email)
if (user === null) {
res.status(401).json({ error: "User not found!" })
break authenticate
}
if ( !verifyPassword(password, user.password) ) {
res.status(403).json({ error: "User not auth!" })
break authenticate
}
const { id, name } = user as IUser
const token = genetareToken({ id, name, email })
res.status(200).send({ token })
} }
xxxxxxxxxx
//break keyword, it breaks out of the switch block
//or from the loop.
break keyword, it breaks out of the switch block
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
//breaking from loop
for(let i=0;i<=100:i++){
console.log(i)
if(i===40){
console.log('Hey you hit 400!');
break;
}
}
//output i from 1 to 40 and at last Hey you hit 400!
xxxxxxxxxx
if (qChanged == "+") {
console.log("Quantity Incremented");
return;
//use return to break the loop
} else if (qChanged == "-");
{
console.log("Quantity Decremented");
}