JavaScript label statementJavaScript label is a statement used to prefix a label as an identifier. You can specify the label by any name other than the reserved words. It is simply used with a colon (:) in code. A label can be used with a break or continue statement to control the flow of the code more precisely. The label is applied to a block of code or a statement. Using some examples, we will learn how to define and use the label statement in JavaScript. SyntaxParameterslabel: It is a JavaScript identifier. Define it by any name that is not a reserved keyword. Statements: It is a JavaScript statement, where break is simply used with the labelled statement and continue with looping labelled statement. ExamplesLet's understand the JavaScript label that how it works and helps to break or continue with the looping statement with the help of different examples. Example: Label with for loop to breakIn this example, we will define two labels by the name innerloop and outerloop, which is used with for loop to break the execution of the loop for a specified condition. Copy Code Test it NowOutput Entering the loop! Outerloop i: 0 Innerloop execution j: 0 Innerloop execution j: 1 Innerloop execution j: 2 Innerloop execution j: 3 Break innermost loop when j>3 Outerloop i: 1 Innerloop execution j: 0 Innerloop execution j: 1 Innerloop execution j: 2 Innerloop execution j: 3 Break innermost loop when j>3 Outerloop i: 2 Break Innerloop when i=2 Outerloop i: 3 Innerloop execution j: 0 Innerloop execution j: 1 Innerloop execution j: 2 Innerloop execution j: 3 Break Innerloop when j>3 Outerloop i: 4 Break Outerloop when i=4 Exit from all loops! Example: Label with for loop to continueIn this example, we will again define two labels by the name innerloop and outerloop. But now they are used with for loop to continue the execution of the loop when the specified condition occurs. Copy Code Test it NowOutput Entering the loop! Outerloop i: 0 Innerloop execution j: 0 Innerloop execution j: 1 Innerloop execution j: 2 Continue Outerloop when j=3 Outerloop i: 1 Innerloop execution j: 0 Innerloop execution j: 1 Innerloop execution j: 2 Continue Outerloop when j=3 Outerloop i: 2 Innerloop execution j: 0 Innerloop execution j: 1 Innerloop execution j: 2 Continue Outerloop when j=3 Outerloop i: 3 Continue Innerloop when i>2 Continue Innerloop when i>2 Continue Innerloop when i>2 Continue Innerloop when i>2 Exit from all loops! Basically, a label statement in JavaScript controls the flow of the program. JavaScript programmers use labels rarely now.
Next TopicJavaScript String with quotes
|