3

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

Emile
  • 33
  • 1
  • 3

3 Answers3

3

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.

Community
  • 1
  • 1
Andrew Li
  • 47,104
  • 10
  • 106
  • 132
  • Thank you all for advising, This works: If you wrote var String = 'String #1'; it should work with no problems. – torazaburo 56 mins ago I will check the other options as well. – Emile Sep 22 '16 at 17:45
3

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");
}
kevin ternet
  • 3,779
  • 2
  • 14
  • 23
1

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>
Adam Buchanan Smith
  • 9,207
  • 5
  • 15
  • 37