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 &< 10; x++) { if (x !== 5) continue; // If the number isn't five, go to the next pass of the loop. console.log(x); } // logs: 5
Using a label with break
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.
Let’s get to that title of this blog post!
// 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 < 10) { x++; for (let y = 0; y < x; y++) { // This will jump back to the top of outerLoop if (y === 5) continue outerLoop; console.log(x,y); } console.log('----'); // This will only happen if x < 6 }
Block statements and labels
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.
Here’s a labeled block statement:
// 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.
위 내용은 JavaScript`if` statement에 레이블을 지정할 수 있습니다의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

Google Fonts가 새로운 디자인 (트윗)을 출시 한 것을 볼 수 있습니다. 마지막 큰 재 설계와 비교할 때 이것은 훨씬 더 반복적 인 느낌이 듭니다. 차이를 간신히 말할 수 있습니다

프로젝트에 카운트 다운 타이머가 필요한 적이 있습니까? 그런 것은 플러그인에 도달하는 것이 당연하지만 실제로는 훨씬 더 많습니다.

새로운 프로젝트가 시작될 때, Sass 컴파일은 눈을 깜박이게합니다. 특히 BrowserSync와 짝을 이루는 경우 기분이 좋습니다.

타탄은 일반적으로 스코틀랜드, 특히 세련된 킬트와 관련된 패턴의 천입니다. tartanify.com에서 우리는 5,000 개가 넘는 타탄을 모았습니다

Inline-Template 지시문을 사용하면 기존 WordPress 마크 업에 대한 진보적 인 향상으로 풍부한 VUE 구성 요소를 구축 할 수 있습니다.

PHP 템플릿은 종종 서브 파 코드를 용이하게하는 데 나쁜 랩을 얻지 만, 그렇지 않아야합니다. PHP 프로젝트가 기본을 시행 할 수있는 방법을 살펴 보겠습니다.

우리는 항상 웹에 더 액세스 할 수 있도록하고 있습니다. 색상 대비는 수학 일 뿐이므로 Sass는 디자이너가 놓친 에지 케이스를 다룰 수 있습니다.
