Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript switch with string variable not working

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

like image 774
Emile Avatar asked Sep 10 '26 17:09

Emile


1 Answers

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.

like image 133
Andrew Li Avatar answered Sep 13 '26 13:09

Andrew Li