gameboyz Posted December 23, 2008 Share Posted December 23, 2008 <body><script type="text/javascript">//You will receive a different greeting based//on what day it is. Note that Sunday=0,//Monday=1, Tuesday=2, etc.var d=new Date();theDay=d.getDay();switch (theDay){case 5: document.write("Finally Friday"); break;case 6: document.write("Super Saturday"); break;case 0: document.write("Sleepy Sunday"); break;default: document.write("I'm looking forward to this weekend!");}</script><script type="text/javascript">if (theDay==5){document.write("Finally Friday");}else if (theDay==6){document.write("Super Saturday");}else if (theDay==0){document.write("Sleepy Sunday");}else{document.write("I'm looking forward to this weekend!");}</script></body> Check this out. Is it possible not to use the switch statement and replace with if else ones? Or will there be circumstances where by it cannot be replaced with if else? Link to comment Share on other sites More sharing options...
jeffman Posted December 23, 2008 Share Posted December 23, 2008 Mostly, though you kind of have it reversed. Switch was invented (I believe) to make a chain of if/else statements more readable.Benchmark tests consistently show little measurable difference (tens of milliseconds) in performance between the two, and that's over hundreds or thousands of iterations.There are of course differences. Multiple if statements can be nested. Case statements can be "added," by leaving out one or more break statements. But the simplest examples can be interchanged with no worries. Link to comment Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.