Rice_Crisp
Rice_Crisp

Reputation: 1261

Javascript "break" always hits

I feel like I'm missing something very basic here. Why doesn't my attached code get to the else statement? It seems to be something with the break statement. This is probably something really simple that I'm just overlooking.

HTML

<button onclick="yo();">Hit me</button>

JS

var line = "no";

function yo() {
    if (line == "yes") {
        break;   
    }
    else {
        window.alert("hi");
    }
}

http://jsfiddle.net/dsX65/

Upvotes: 1

Views: 94

Answers (3)

Rick Viscomi
Rick Viscomi

Reputation: 8852

I think you meant to use the return statement instead.

var line = "no";

function yo() {
    if (line == "yes") {
        return;   
    }
    else {
        window.alert("hi");
    }
}

Still, you can do better:

var line = "no";

function yo() {
    if (line !== "yes") {
        window.alert("hi");
    }
}

Upvotes: 1

kemiller2002
kemiller2002

Reputation: 115488

Use return instead of break and that will fix it.

Upvotes: 1

VisioN
VisioN

Reputation: 145408

Because you have a syntax error.

break statement can be used in loops and switch statements and can't be used in if clause.

break

Terminates the current loop, switch, or label statement and transfers program control to the statement following the terminated statement.

(... from MDN ...)

Upvotes: 3

Related Questions