user14532940
user14532940

Reputation:

Random 'undefined' gets inserted into string

I have a function that takes in an integer and returns it in reverse reverse(-425) -> -524

let reverse = (x) => {
  let y = x.toString()
  let char = y.length - 1
  let z = ''
  if (y[0] === '-') {
    z = '-'
    y = y.slice(1, y.length)
  }

  while (char >= 0) {
    z += y[char]
    char -= 1
  }

  return z
}

console.log(reverse(-324))

When I run console.log(reverse(-324)) I expect it to return -423 but instead I get -undefined423.

Where is undefined coming from?

Upvotes: 0

Views: 80

Answers (1)

Quentin
Quentin

Reputation: 944170

You work out the first value of char (which depends on the length of the string) before you check to see if the number is negative.

If the number is negative you reduce the length of the string by 1 as you remove the - from the front.

At this point char is one too high.

Change the order you do those things:

let reverse = (x) => {
  let y = x.toString()
  let z = ''
  
  if (y[0] === '-') {
    z = '-'
    y = y.slice(1, y.length)
  }

  let char = y.length - 1

  while (char >= 0) {
    z += y[char]
    char -= 1
  }

  return z
}

console.log(reverse(-324))
console.log(reverse(2468))

Upvotes: 1

Related Questions