Skip to content
Advertisement

return statement in function that convert decimal to binary numbers

I’m trying to understand how to use functions in JS.

This code converting decimal numbers to binary numbers:

for (j = 13; j <= 16; j++) {
  res = ""
  number = j

  while (number > 0) {
    res = res + number % 2
    number = Math.floor(number / 2)
  }

  len = res.length

  rev=""

  for (i = 1; i <= len; i++) {
    rev = rev + res[res.length - i]
  }
  
  console.log(rev)
}

but when I’m trying to put this code into a function, the function returns only the first or the last value. What am I doing wrong?

function f(min, max) {
  for (j = min; j <= max; j++) {
    res = ""
    number = j
    
    while (number > 0) {
      res = res + number % 2
      number = Math.floor(number / 2)
    }

    len = res.length

    rev=""

    for (i = 1; i <= len; i++) {
      rev = rev + res[res.length-i]     
    }  
  }
  return rev
}

console.log(f(13,15))

Advertisement

Answer

You have to store the result of each iteration in array.

function f(min, max) {
  const results = []
  for (j = min; j <= max; j++) {
    res = ""
    number = j
    
    while (number > 0) {
      res = res + number % 2
      number = Math.floor(number / 2)
    }

    len = res.length

    rev=""

    for (i = 1; i <= len; i++) {
      rev = rev + res[res.length-i]     
    }
    
    results.push(rev)
  }
  return results
}

console.log(f(13,15))

Also you should declare your variables in JavaScript, because not doing that can lead to bugs https://www.geeksforgeeks.org/what-happen-when-we-directly-assign-the-variable-without-declaring-it-in-javascript/

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement