Reputation: 33
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
Upvotes: 3
Views: 13915
Reputation: 61
Another simple solution is to concat a primitive string and your string object. The result is a primitive string, which can be used in a switch statement.
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');
}
Upvotes: 0
Reputation: 57964
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.
Upvotes: 4
Reputation: 9457
You can change the object to a string using toString()
See example https://jsfiddle.net/DIRTY_SMITH/59x9xn3g/1/
<script>
var someObject =new String('String #1');
var someString = someObject.toString();
document.write(someString);
document.write(' Check ');
switch(someString)
{
case 'String #1' : document.write('String Number 1');
break;
default: document.write('wrong string');
}
</script>
Upvotes: 2
Reputation: 4612
You must compare an Object with an Object not a String with an Object. Here I compare an object with an Object :
var string = "String #1";
console.log(string);
console.log("Check");
switch(string)
{
case "String #1":
console.log("String Number 1");
break;
default: console.log("wrong string");
}
Upvotes: 3