Search code examples
javascriptparametersswitch-statement

How to set a default parameter value if no argument is passed through using the switch statement condition?


I'm doing a lab exercise on VScode for an assignment and I'm unable to pass one of the Mocha test requirements. This test requires "takes in two arguments, a name and a language, and language defaults to JavaScript". I've tried to default it to "Javascript" value assuming it wants a switch statement. This is the following requirements:

describe('introductionWithLanguageOptional(name, language)', function() {
  it('takes in two arguments, a name and a language, and language defaults to JavaScript', function() {
    expect(introductionWithLanguageOptional("Gracie")).toEqual("Hi, my name is Gracie and I am learning to program in JavaScript.");
  })
})

Quite frankly, I've confused myself.

This is what I've tried:

function introductionWithLanguageOptional(name, language = "Javascript") {
  switch (name, language) {
    case (name, language):
      return `Hi, my name is ${name} and I am learning to program in ${language}.`
      break;
    default:
      return `Hi, my name is ${name} and I am learning to program in ${language}.`
  }
}

console.log(introductionWithLanguageOptional("Gracie"))

Output:

Hi, my name is Gracie and I am learning to program in undefined.

Solution

  • Your switch-case basically checks whether language equals itself ((name, language) evaluates to language as pointed out in the comment-section), which is always true, making your switch-case superfluous. And your default does exactly the same as your case. Let's get rid of it, like:

    function introductionWithLanguageOptional(name, language= "Javascript"){
        return `Hi, my name is ${name} and I am learning to program in ${language}.`
    }
    

    The default value of language is the value language will have if you do not specify it. No need to manually set it.

    EDIT

    let name = 'nm', language = 'lng';
    
    switch (name, language) {
        case (name, language): console.log("(name, language) equals itself"); break;
        default: console.log("something else happened");
    }
    
    switch(name, language) {
        case (language ,name): console.log("something else happened"); break;
        default: console.log("inverted name and language");
    }