Click here to Skip to main content
15,063,287 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
JavaScript
switch(prompt("Whatistheweatherlike?"))


{
case"rainy":
console.log("Remembertobringanumbrella.");
break;
case"sunny":
console.log("Dresslightly.");
case"cloudy":
console.log("Gooutside.");
break;
default:
console.log("Unknownweathertype!");
break;
}


My question is how the first line works?

switch(prompt("Whatistheweatherlike?"))

Basically, we are comparing user input and printing a message.

Usually, we use prompt("message",""); to store a variable. My question is why we havnt stored value in any variable?
Posted

A switch statement is basically an if statement, that doesn't repeat the question.

What you have above is the functional equivalent of:

JavaScript
var response = switch(prompt("Whatistheweatherlike?"));

if(response == rainy) {
console.log("Remembertobringanumbrella.");
}
else if(response == "sunny") {
console.log("Dresslightly.");
}
else if(response == "cloudy") {
console.log("Gooutside.");
}
else {
console.log("Unknownweathertype!");
}
   
v2
Comments
ankur1163 2-Jan-15 14:57pm
   
so, in switch statement. if(response==rainy) is automatically done in the background. correct?
Doug Vanderweide 2-Jan-15 15:05pm
   
Yes.
Well,
this is quite simple.
When you run this and switch gets hit, it prompts the user to input What the weather is like?
Window Prompt() in javascript means that everything in the window gets overboard by the prompt dialog or dialog, which asks the user to input based on the questions with a Ok and Cancel button, On click of Ok, the Case statements gets checked and the output message gets logged.
And based on the input by the user case is checked and output message is printed in the console log.
Fiddle[^]
Please check the fiddle also.
I hope this helps.
Thanks.:)
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900