Could anyone tell me why the below switch is not working?
var String=new String('String #1');
document.write(String);
document.write(' Check ');
switch(String)
{
case 'String #1' :
document.write('String Number 1');
break;
default: document.write('wrong string');
}
The output is: String #1 Check wrong string
String is a constructor that's builtin to JavaScript. Naming variables that shadow these constructors will cause an error:
TypeError: String is not a constructor
Rename the String variable and do not use the switch statement here because you have a String instance. switch statements use strict comparison (===) per the MDN documentation and the ECMAScript 2015 specification. Since a string instance and literal are never 'strictly equal', comparison fails. Don't instantiate, instead use a literal:
var string = "String #1";
switch(string) {
case "String #1":
document.write("String Number 1");
break;
default:
document.write("wrong string");
}
Also, I don't recommend using document.write, see here. Logging or inserting into the DOM with createElement and appendChild should work sufficiently here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With