suchen
HeimWeb-FrontendCSS-TutorialSie können eine JavaScript `if` -Anweisung kennzeichnen

You Can Label a JavaScript `if` Statement

Labels are a feature that have existed since the creation of JavaScript. They aren’t new! I don’t think all that many people know about them and I’d even argue they are a bit confusing. But, as we’ll see, labels can be useful in very specific instances.

But first: A JavaScript label should not be confused with an HTML

A JavaScript label is a way to name a statement or a block of code. Typically: loops and conditional statements. That allows you to break or continue the labeled statement from within. To apply a label to a statement, start the statement with label: and whatever you put as “label” will be the label you can reference later.

Here’s the basic syntax for a label:

let x = 0;
// Label a loop as "myLoop"
myLoop:
while (true) {
  if (x >= 10) {
    // This will cause "myLoop" to end.
    break myLoop;
  }
  x++;
}

Labels are only an internal reference to a statement and are not something that can be looked up, exported, or stored in a value. They also do not conflict with variable names, so if you really want to confuse people, you can have a loop and a variable be the same name! Please don’t do this —  future you, and anyone else that has to read your code will appreciate it. The use cases for labels are limited, but incredibly powerful in the right hands.

A brief intro to break and continue

Let’s back up a bit and talk about break and continue. A break statement will terminate the currently running loop or conditional statement. It is most commonly used in a switch statement to end a case, but it can also be used to end an if statement early, or also to cause a for or while loop to end and stop looping. It’s a great way to escape out of a conditional statement or end a loop early.

Here’s a basic example of break in use:

const x = 1;
switch(x) {
  case 1:
    console.log('On your mark!');
    break; // Doesn't check the rest of the switch statement if 1 is true
  case 2:
    console.log('Get set!');
    break; // Doesn't check the rest of the switch statement if 2 is true
  case 3:
    console.log('GO!');
    break; // Doesn't check the rest of the switch statement if 3 is true
}
// logs: 'On your mark!'

Similarly, the continue statement can be used with loops to end the current iteration early, and start the next run of the loop. This will only work inside of loops however.

Here’s continue in use:

for (let x = 0; x &


<h3 id="Using-a-label-with-break">Using a label with break</h3>


<p>Typically, a use case for labels comes up when you get into nested statements of any kind. Using them with break can stop a deeply nested loop or conditional and make it stop immediately.</p>



<p>Let’s get to that title of this blog post!</p>



<pre rel="JavaScript" data-line="">// Our outer if statement
outerIf: 
if (true) {
  // Our inner if statement
  innerIf:
  if (true) {
    break outerIf; // Immediately skips to the end of the outer if statement
  }
  console.log('This never logs!');
}

There you have it, you can label an if statement.

Using a label with continue

There have been times where I have made a nested loop and wanted to skip over some iterations of the outer loop while inside the inner loop. I usually wind up breaking the inner loop, then checking to see if I’m in the state I want to skip, then continue the outer loop. Being able to simplify that code down into an easier to read statement is great!

let x = 0;
outerLoop:
while (x 


<h3 id="Block-statements-and-labels">Block statements and labels</h3>


<p>Block statements in JavaScript are a way to scope your const and let variables to only a portion of your code. This can be useful if you want to localize some variables without having to create a function. The (big) caveat to this is that block statements are invalid in strict mode, which is what ES modules are by default.</p>



<p>Here’s a labeled block statement:</p>



<pre rel="JavaScript" data-line="">// This example throws a syntax error in an ES module
const myElement = document.createElement('p');
myConditionalBlock: {
  const myHash = window.location.hash;
  // escape the block if there is not a hash.
  if (!myHash) break myConditionalBlock;
  myElement.innerText = myHash;
}
console.log(myHash); // undefined
document.body.appendChild(myElement);

Real world usage

It took me a while to come up with a reason to use a label in everyday production code. This might be a bit of a stretch, but a place where a label in JavaScript might come in handy is to escape early from a loop while inside a switch statement. Since you can break while in a switch, being able to apply a label to a loop that ends it early could potentially make your code more efficient.

Here’s how we might use that in a calculator app:

const calculatorActions = [
  { action: "ADD", amount: 1 },
  { action: "SUB", amount: 5 },
  { action: "EQ" },
  { action: "ADD", amount: 10 }
];
    
let el = {};
let amount = 0;
calculate: while (el) {
  // Remove the first element of the calculatorActions array
  el = calculatorActions.shift();
  switch (el.action) {
    case "ADD":
      amount += el.amount;
      break; // Breaks the switch
    case "SUB":
      amount -= el.amount;
      break; // Breaks the switch
    case "EQ":
      break calculate; // Breaks the loop
    default:
      continue calculate; // If we have an action we don't know, skip it.
  }
}

This way, we can bail out of the calculate loop when a condition is matched rather than allowing the script to continue!

Conclusion

It’s rare that you will need to use a JavaScript label. In fact, youcan lead a very fulfilling career without ever knowing that this exists. But, on the offhand chance you find that one place where this syntax helps out, you’re now empowered to use it.

Das obige ist der detaillierte Inhalt vonSie können eine JavaScript `if` -Anweisung kennzeichnen. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Stellungnahme
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Ankerpositionierung kümmert sich nur um die QuellenreihenfolgeAnkerpositionierung kümmert sich nur um die QuellenreihenfolgeApr 29, 2025 am 09:37 AM

Die Tatsache, dass die Ankerpositionierung die HTML-Quellenreihenfolge vermeidet, ist so CSS-y, weil sie eine weitere Trennung von Bedenken zwischen Inhalt und Präsentation ist.

Was bedeutet Margin: 40px 100px 120px 80px?Was bedeutet Margin: 40px 100px 120px 80px?Apr 28, 2025 pm 05:31 PM

In Artikel wird die CSS -Margin -Eigenschaft erörtert, insbesondere "Margin: 40px 100px 120px 80px", seine Anwendung und Auswirkungen auf das Webseitenlayout.

Was sind die verschiedenen CSS -Grenzeigenschaften?Was sind die verschiedenen CSS -Grenzeigenschaften?Apr 28, 2025 pm 05:30 PM

In dem Artikel werden die CSS -Grenzeigenschaften erörtert und sich auf Anpassung, Best Practices und Reaktionsfähigkeit konzentriert. Hauptargument: Border-Radius ist für reaktionsschnelle Designs am effektivsten.

Was sind CSS -Hintergründe, listen Sie die Eigenschaften auf?Was sind CSS -Hintergründe, listen Sie die Eigenschaften auf?Apr 28, 2025 pm 05:29 PM

In dem Artikel werden CSS -Hintergrundeigenschaften, deren Verwendungszwecke für die Verbesserung des Website -Designs und die zu vermeidenen Fehler erläutert. Der Hauptaugenmerk liegt auf reaktionsschnellem Design unter Verwendung der Hintergrundgröße.

Was sind CSS HSL -Farben?Was sind CSS HSL -Farben?Apr 28, 2025 pm 05:28 PM

In Artikel werden CSS HSL -Farben, ihre Verwendung im Webdesign und die Vorteile gegenüber RGB erörtert. Der Schwerpunkt liegt auf der Verbesserung des Designs und der Zugänglichkeit durch intuitive Farbmanipulation.

Wie können wir Kommentare in CSS hinzufügen?Wie können wir Kommentare in CSS hinzufügen?Apr 28, 2025 pm 05:27 PM

In dem Artikel wird die Verwendung von Kommentaren in CSS erörtert, in denen Einzellinien- und Multi-Line-Kommentarsyntaxe beschrieben werden. Es wird argumentiert, dass die Kommentare die Lesbarkeit, die Wartbarkeit und die Zusammenarbeit von Code verbessern, sich jedoch auf die Leistung der Website auswirken können, wenn sie nicht ordnungsgemäß verwaltet werden.

Was sind CSS -Selektoren?Was sind CSS -Selektoren?Apr 28, 2025 pm 05:26 PM

In dem Artikel werden CSS -Selektoren, ihre Typen und die Verwendung zum Styling von HTML -Elementen erörtert. Es vergleicht ID- und Klassenauswahlern und befasst sich mit Leistungsproblemen mit komplexen Selektoren.

Welche Art von CSS hat die höchste Priorität?Welche Art von CSS hat die höchste Priorität?Apr 28, 2025 pm 05:25 PM

In dem Artikel wird die CSS -Priorität erläutert und sich auf Inline -Stile mit der höchsten Spezifität konzentriert. Es erklärt Spezifitätsniveaus, übergeordnete Methoden und Debugging -Tools zur Verwaltung von CSS -Konflikten.

See all articles

Heiße KI -Werkzeuge

Undresser.AI Undress

Undresser.AI Undress

KI-gestützte App zum Erstellen realistischer Aktfotos

AI Clothes Remover

AI Clothes Remover

Online-KI-Tool zum Entfernen von Kleidung aus Fotos.

Undress AI Tool

Undress AI Tool

Ausziehbilder kostenlos

Clothoff.io

Clothoff.io

KI-Kleiderentferner

Video Face Swap

Video Face Swap

Tauschen Sie Gesichter in jedem Video mühelos mit unserem völlig kostenlosen KI-Gesichtstausch-Tool aus!

Heiße Werkzeuge

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Leistungsstarke integrierte PHP-Entwicklungsumgebung

EditPlus chinesische Crack-Version

EditPlus chinesische Crack-Version

Geringe Größe, Syntaxhervorhebung, unterstützt keine Code-Eingabeaufforderungsfunktion

PHPStorm Mac-Version

PHPStorm Mac-Version

Das neueste (2018.2.1) professionelle, integrierte PHP-Entwicklungstool

Herunterladen der Mac-Version des Atom-Editors

Herunterladen der Mac-Version des Atom-Editors

Der beliebteste Open-Source-Editor

WebStorm-Mac-Version

WebStorm-Mac-Version

Nützliche JavaScript-Entwicklungstools