Alex Cabello
Alex Cabello

Reputation: 13

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.

Upvotes: 1

Views: 2606

Answers (2)

Carson
Carson

Reputation: 152

you've declared variable x and not set value for it, and = just for left assign follows my code

Heres my code:

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

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

your codes error:

  1. variable x redeclared
  2. x=10 means let 10 assigns to variable x.

hopes to help you

edited:

for your question, maybe this code will be better

function unit(x){
    var nickname = '';
    switch(x){
        case 10:
            nickname = 'kibi';
            break;
        case 20:
            nickname = 'Mebi';
            break;
        case 30:
            nickname = 'Gibi';
            break;
    }
    return nickname;
}

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

I tell you

Variables should not have ambiguity, one variable do one thing.

you can follow to @epascarello and @Keith advice

Upvotes: 1

MUlferts
MUlferts

Reputation: 1330

All that is changed in this snippet was exactly what the two comments suggested. Remove the extra initialization of x and change "=" to "==" in the comparisons.

function unit(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");

Upvotes: 0

Related Questions