dimanche 18 février 2018

Different outputs using switch and if else statements in JavaScript

I am a beginner in learning programming, more specifically JavaScript. I have come across a small problem while studying coding. When I use switch statements to solve a piece of problem, it produces right output.

var dateNow = 3;
var dateSuffix;

switch (dateNow) {
  case 1:
  case 21:
  case 31:
    dateSuffix = "st";
    break;
  case 2:
  case 22:
    dateSuffix = "nd";
    break;
  case 3:
  case 23:
    dateSuffix = "rd";
    break;
  default:
    dateSuffix = "th";
    break;
}

console.log("Today is the " + dateNow + dateSuffix + " day.");
    

But when I do the same with if else statements, the output is wrong.

var dateNow = 3;
var dateSuffix;

if (dateNow == 1 || 21 || 31) {
  dateSuffix = "st";
} else if (dateNow == 2 || 22) {
  dateSuffix = "nd";
} else if (dateNow == 3 || 23) {
  dateSuffix = "rd";
} else {
  dateSuffix = "th";
}

console.log("Today is " + dateNow + dateSuffix + " day of the month...");

Could anyone please point out the problem with my if statements?

Aucun commentaire:

Enregistrer un commentaire