iksheth
iksheth

Reputation: 153

JS can not change variable

I am trying to make reverse Int function which is as below.

function reverseInt(nx) {
  var n = nx
  const isNeg = n < 0 ? () => { n = n * -1; return true; } : false;
  return parseInt(("" + n).split("").reverse().join('') * ((isNeg)? -1 : 1));
}

Here in line 2, I am trying to change value of n id n is negative but it is not getting updated. Please let me know where I am making mistake.

Thank you.

Upvotes: 1

Views: 72

Answers (2)

KaratemanJohnson
KaratemanJohnson

Reputation: 161

I think youre going a little overboard with that ternary. In the future try to keep your variables more clearly defined. You have here that isNeg can be either a boolean or a function, when all you really need is a flag. The reason your n's value was never changing was because you were never invoking isNeg.

function reverseInt(nx) {
  let n = nx;
  let isNeg;
  if (n < 0) {
    isNeg = true;
    n = n * -1
  }
  return parseInt(("" + n).split("").reverse().join('') * ((isNeg)? -1 : 1));
};

Upvotes: 0

Don
Don

Reputation: 4157

You're never executing the function in line 2. If n < 0 then you're setting isNeg to a function then using that function as a boolean value.

I'd recommend not trying to get fancy with things like this, just expand out the if statement:

function reverseInt(nx) {
  var n = nx
  const isNeg = n < 0;
  if( isNeg ){
      n = -n;
  }
  return parseInt(("" + n).split("").reverse().join('') * ((isNeg)? -1 : 1));
}

Upvotes: 4

Related Questions