Question

I'm working on switch statements and I've been trying to make this code right here work, but it doesn't seem to output the correct console.log case string.

var user = prompt("What is your name?").toLowerCase();
switch(user){
    case "luka":
    console.log("What a beautiful name, my name is exactly the same :) Hi Luka! :D");
    break;

    case user.length > 10:
    console.log("That's a long name!");
    break;

    case user.length < 4:
    console.log("Not to be rude or impolite to you in any way, but your name is kinda       short :( Not that it isn't cool or something :D");
    break;

}

I've tried putting paranthesis around the user like this (user).length < 4, but that doesn't work, nor some of my other tries. Does anybody know how to implement this correctly?

Était-ce utile?

La solution 2

There is one possible workaround for using switch in the cases like yours:

var user = prompt("What is your name?").toLowerCase();
switch (true) {
    case (user === "luka"):
        console.log("What a beautiful name, my name is exactly the same :) Hi Luka! :D");
        break;

    case (user.length > 10):
        console.log("That's a long name!");
        break;

    case (user.length < 4):
        console.log("Not to be rude or impolite to you in any way, but your name is kinda       short :( Not that it isn't cool or something :D");
}

However I'd follow @epascarello's advice and use if/else blocks.

Autres conseils

You should not use conditionals in a switch statement.

Use if/else if

var user = prompt("What is your name?").toLowerCase();
if (user==="luka") {
    console.log("What a beautiful name, my name is exactly the same :) Hi Luka! :D");
} else if (user.length > 10) {
    console.log("That's a long name!");
} else if (user.length < 4) {
    console.log("Not to be rude or impolite to you in any way, but your name is kinda       short :( Not that it isn't cool or something :D");
} else {
    console.log("in else");
}

That's just not how JavaScript switch statements work. The values in the "case" expressions are compared to the value of the switch expression.

The statement you have there is equivalent to:

if (user === "luka") {
    console.log("What a beautiful name, my name is exactly the same :) Hi Luka! :D");
}
else if (user === (user.length > 10)) {
    console.log("That's a long name!");
}
else if (user === (user.length < 4)) {
    console.log("Not to be rude or impolite to you in any way, but your name is kinda       short :( Not that it isn't cool or something :D");    
}

Thus, you're comparing the value of "user" to the results of comparing user.length to those values. Those comparison results are boolean, so "use" will never be === to them.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top