I'm currently working on a codewars kata (Convert RGB number (0-255) to hexadecimal) and came across something interesting when trying to improve the readability of my code. I want to construct a global function to work with local variables, but when I try to run the code it throws an undefined error on the "j" variable (and also presumably the "i" variable). Code below:
function rgb(r, g, b){
  let x
  let y
  let z
  function conversion(){
    switch(j) {
            case 10:
              j = 'A'
              break
            case 11:
              j = 'B'
              break
            case 12:
              j = 'C'
              break
            case 13:
              j = 'D'
              break
            case 14:
              j = 'E'
              break
            case 15:
              j = 'F'
          }
          switch(i) {
            case 10:
              i = 'A'
              break
            case 11:
              i = 'B'
              break
            case 12:
              i = 'C'
              break
            case 13:
              i = 'D'
              break
            case 14:
              i = 'E'
              break
            case 15:
              i = 'F'
          }
  }
  if (r <= 0) {
    x = '00'
  } else if (r >= 255) {
      x = 'FF'
    } else {
        let i = Math.floor(r / 16)
        let j = Math.floor(r - i * 16)
        conversion()
        x = i.toString() + j.toString()
      }
  if (g <= 0) {
    y = '00'
  } else if (g >= 255) {
      y = 'FF'
    } else {
        let i = Math.floor(g / 16)
        let j = Math.floor(g - i * 16)
        conversion()
        y = i.toString() + j.toString()
      }
  if (b <= 0) {
    z = '00'
  } else if (b >= 255) {
      z = 'FF'
    } else {
        let i = Math.floor(b / 16)
        let j = Math.floor(b - i * 16)
        conversion()
        z = i.toString() + j.toString()
      }
  return x + y + z
}
So as you can see, it would be nicer to use the "conversion" function rather than copy paste all that code three times. Any ideas on this topic? Thanks in advance.
 
     
     
     
    