mercredi 27 septembre 2017

If/else inside function JavaScript

Please don't be too hard on me as I've just started in school and I'm using Ubuntu. I've written this code (which might be the simplest code ever) that simply tells about the conversion of bytes into other units (Mebi, Kibi...). When I use the console.log it always displays Kibi.

function unit(x){
 var x;
 if (x=10){
  x='Kibi';
 } else if (x=20){
   x='Mebi';
 } else if (x=30){
   x='Gibi';
 }
 return x;
}

console.log("2^10 bytes are 1 " + unit(10) + "byte");
console.log("2^20 bytes are 1 " + unit(20) + "byte");
console.log("2^30 bytes are 1 " + unit(30) + "byte");

The thing here is that as I said it always displays Kibi on all console outputs, the funny thing for me that I don't understand is that if I change the first console.log for

console.log('2^10 bytes are 1 ' + unit(20) + 'byte'

it will still display all console outputs with Kibi even if I never called unit(10).

I really don't understand why this is happening and any help would be greatly apprecieated. Thank you.

Aucun commentaire:

Enregistrer un commentaire