Labelled statement issue

Somebody should, please tell me what’s with this code.

const myBtn = document.querySelector('button');

const inputF = document.querySelector('input');

myBtn.addEventListener('click', function () {

  if (inputF.value === 'sam') {

    break breaker;



breaker: while (true) {



// breaker: for (;;) {

//     console.log('infinite');

// }

i’m getting Uncaught SyntaxError: Undefined label 'breaker' error.

I’m am trying to make infinite loop break on button click.

if (inputF.value === 'sam') {

    break breaker;


^JavaScript is referring to that breaker that you wrote.

The code isn’t working. And i don’t why. Every statement seems alright to me.

    break breaker;

This is not a valid line of code. breaker doesn’t mean anything.

But I labelled the while loop breaker. Or is the labelling wrong?

What i am trying to do is break out of the loop supposedly labelled breaker.

Initially, i successfully used an inner loop to break out of an outer loop. But then, i learnt that i could use a button click or so to break out of a loop. Which is why i wrote this code.

The following code also uses break statements with labeled blocks, but generates a SyntaxError […] A break statement must always be nested within any label it references

Turns out that my logic won’t work. I’d have to dynamically set the while loop condition to be false when the button is clicked.
But then, is there is a way to go around this still sticking with the labelled statement? I am convinced it’s possible. But i can’t just think straight enough.
Thank you for your help @ArielLeslie

If it’s any consolation, things like break statements are considered to be bad practice because they lead to spaghetti code.

1 Like

Thank you, i really appreciate.

You definitely do not need to use a labeled statement. Using labels is pretty much the worse form of flow control there is. I wouldn’t even bother learning about it.

I’m a little bit confused what it is you are trying to achieve with your code, can you explain what it is you want to have happen?

1 Like

I want it such that if i click on the button element, the infinite loop will cease to continue.

What is the point of the infinite loop? What exactly are you trying to achieve with the code? The infinite loop is just going to block/spam the browser with log statements.

You have an event listener, it checks for an input value, if the value is the right value you do something, otherwise, you do nothing.

1 Like

Just practicing.
Thank you. I now understand it better.