Search code examples
javascriptswitch-statementcase

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


Solution

  • 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");
    }