Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

ReferenceError: key is not defined

I am writing an algorithm for a roman numeral converter. This solution works perfectly on my VS Code but gives me the "ReferenceError: key is not defined" error on freeCodeCamp.

function convertToRoman(num) {
  let romanNumerals = {
    M: 1000,
    CM: 900,
    D: 500,
    CD: 400,
    C: 100,
    XC: 90,
    L: 50,
    XL: 40,
    X: 10,
    IX: 9,
    V: 5,
    IV: 4,
    I: 1
  }

  let answer = "";
  let numTemp = num;
  let decimal = 0;
  let remainder = 0;

  if (num == 0) answer = 0;
  if (num > 0)  {
    let romanArr = Object.entries(romanNumerals);
    for ([key, value] of romanArr) {
      if (numTemp / value >= 1) {
        decimal = Math.floor(numTemp / value);
        remainder = numTemp % value;
        answer += key.repeat(decimal);
        numTemp = remainder;
      } 
    }
  }
  return answer;
 }
 
  console.log(convertToRoman(2014));
  console.log(convertToRoman(3999));

I don’t know what to do. Can anyone help please?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Your loop variables should be declared with const, let, or var.

for (let [key, value] of romanArr) {

By setting strict mode at the top, and removing the declaration, you will see the error you described above:

ReferenceError: key is not defined

The freeCodeCamp editor may set strict mode internally when you execute your snippet.

Working example

'use strict';

function convertToRoman(num) {
  let romanNumerals = {
    M: 1000,
    CM: 900,
    D: 500,
    CD: 400,
    C: 100,
    XC: 90,
    L: 50,
    XL: 40,
    X: 10,
    IX: 9,
    V: 5,
    IV: 4,
    I: 1
  }

  let answer = "";
  let numTemp = num;
  let decimal = 0;
  let remainder = 0;

  if (num == 0) answer = 0;
  if (num > 0) {
    let romanArr = Object.entries(romanNumerals);
    for (let [key, value] of romanArr) {
      if (numTemp / value >= 1) {
        decimal = Math.floor(numTemp / value);
        remainder = numTemp % value;
        answer += key.repeat(decimal);
        numTemp = remainder;
      }
    }
  }
  return answer;
}

console.log(convertToRoman(2014));
console.log(convertToRoman(3999));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading