skip to Main Content

so I am making a converter from Decimal to Binary using JS and HTML. I’m nearly finished with my task, but my code keeps printing ‘undefined‘ along with the answer.

For example, if I enter the number 9, I will get an output of:

0bundefined1001

Why is the ‘undefined’ there, and how do I get rid of it?

// NECESSARY VARIABLES DEFINED
let decimalNum; // User's input
let binaryNum; // (soon) converted decimalNum
let x = 0; // explained in the algorithm 

// THIS FUNCTION CHECKS WHETHER THE USER'S INPUT IS A NATURAL NUMBER
function is_Natural(n) {
  if (typeof n !== 'number')
    return 'Not a number';
  return (n > 0) && (Math.floor(n) === n) && n !== Infinity;
}

// THIS SECTION CONVERTS THE USER'S INPUT TO THE BINARY SYSTEM
document.getElementById("mySubmit").onclick = function() {
  decimalNum = document.getElementById("decimalNum").value; //retrieves the user's input and stores it in the previously defined variable
  decimalNum = Number(decimalNum)
  if (is_Natural(decimalNum) === true) {
    while (true) {
      if (decimalNum < 2 ** x) {
        x = x - 1 // For it to let the left-most value be equal to 1
        break
      } else {
        x = x + 1
      }
    }
    while (true) {
      if (decimalNum >= 2 ** x) {
        binaryNum = binaryNum + '1';
        decimalNum = decimalNum - 2 ** x;
        x = x - 1
      } else {
        binaryNum = binaryNum + '0'
        x = x - 1
      }
      if (x < 0) {
        break
      } else {
        continue
      }
    }
  }
  document.getElementById("binaryNum").textContent = `Here is your number in the Binary system: 0b${binaryNum}`; // replaces the placeholder
}
<h1> Converter from Decimal to Binary</h1>
<label for="decimalNum" title="A positive whole number (1, 2, 3, etc.), excluding 0 and inifinity."> Decimal (natural number) </div>: </label>
<input id="decimalNum" type="number">
<button id="mySubmit"> Submit </button>
<p id="binaryNum"> </p>
<!-- Placeholder for the printed form in the Binary system.-->
<i> Please note that the <b>0b</b> index in the Binary number is a prefix to indicate its system.</i>

2

Answers


  1. the binaryNum variable without initializing it with an empty string. as an output it starts with the undefined (the default value for an uninitialized variable in JavaScript for let,var).

    Login or Signup to reply.
  2. ‘binaryNum’ requires a default value

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search