Search code examples
javascriptfunctionreturn

Return function returns nothing


I am using this function in js(it should return the special subject) :

function getSubjectByNumber(subject_number) {

  var subject_name;

  if (subject_number === 0) {
    return subject_name = "Deutsch";
  }
  if (subject_number === 1) {
    return subject_name = "Englisch";
  }
  if (subject_number === 2) {
    return subject_name = "Latein";
  }
  if (subject_number === 3) {
    return subject_name = "Kunst";
  }
  if (subject_number === 4) {
    return subject_name = "Musik";
  }
  if (subject_number === 5) {
    return subject_name = "Instrument/G. (Additum)";
  }
  if (subject_number === 6) {
    return subject_name = "Französisch (spät.)";
  }
  if (subject_number === 7) {
    return subject_name = "Theater und Film";
  }
  ..//That goes a long time...
}

And I call the return method with this code line:

var subject_name = getSubjectByNumber(subject);   

But as I see it returns nothing (''), because the var subject_name stays always empty. I hope anyone can help me. Thanks in advance.
~mb


Solution

  • You are using the strict equality operator (===), which doesn't do any type conversion on the operands. If subject is a String, then that would explain it because "0" === 0 is false. In this scenario, you need to either convert subject to a number (just prepending + to it would do it) or use == to do an equality with conversion check.

    But, all your if/then logic as well as the string/number issue can be eliminated if you just use an array.

    let subjects = ["Deutsch", "Englisch", "Latein", "Kunst", "Musik", "Instrument/G. (Additum)", "Französisch (spät.)", "Theater und Film"];
    
    function getSubjectByNumber(subject_number) {
      return subjects[subject_number];
    }
    
    console.log(getSubjectByNumber(0));
    console.log(getSubjectByNumber("0"));
    console.log(getSubjectByNumber(6));
    console.log(getSubjectByNumber(7));