What does break do in javascript?

Software
AffiliatePal is reader-supported. When you buy through links on our site, we may earn an affiliate commission.

Listen

Introduction

In JavaScript, the break statement is a control flow statement that is used to terminate a loop or switch statement. When encountered, it immediately exits the loop or switch statement and resumes execution at the next statement after the loop or switch.

Using break in loops

The most common use of the break statement is to exit a loop prematurely. When placed inside a loop, it causes the loop to terminate immediately, regardless of whether the loop condition is still true or not. This can be useful when you want to stop iterating through a loop based on a certain condition.

For example, consider the following code snippet:

“`javascript
for (let i = 1; i <= 10; i++) { if (i === 5) { break; } console.log(i); } ``` In this case, the loop will iterate from 1 to 10. However, when the value of i becomes 5, the break statement is encountered and the loop is terminated. As a result, only the numbers 1, 2, 3, and 4 will be printed to the console.

Using break in switch statements

The break statement is also commonly used in switch statements. It allows you to exit the switch statement and prevent the execution of any further code blocks.

Consider the following example:

“`javascript
let day = 3;
let dayName;

switch (day) {
case 1:
dayName = ‘Monday’;
break;
case 2:
dayName = ‘Tuesday’;
break;
case 3:
dayName = ‘Wednesday’;
break;
default:
dayName = ‘Unknown’;
break;
}

console.log(dayName);
“`

In this case, the value of the variable day is 3. The switch statement checks the value of day and assigns the corresponding day name to the variable dayName. Since the value is 3, the code block for case 3 is executed, and the break statement is encountered. This causes the switch statement to exit, and the value of dayName is set to ‘Wednesday’. Without the break statement, the code would continue to execute the code blocks for subsequent cases.

Conclusion

The break statement in JavaScript is a powerful tool for controlling the flow of execution in loops and switch statements. It allows you to terminate a loop prematurely or exit a switch statement, preventing the execution of any further code blocks. Understanding how and when to use the break statement can greatly enhance your ability to write efficient and effective JavaScript code.

References

– developer.mozilla.org
– www.w3schools.com