Tell us what’s happening:
Sorry if this is a silly question, but I’ve been getting many of these kind of undefined errors so far while I’ve been doing this course.
Why does it tell me that z is not defined?
I return it from the function I created, in order to use it in the subsequent part of the code. So I can’t understand what I must be doing wrong.
Although it is a local variable within the function findingBeginning, it becomes a global variable after I have returned it, no?
Thanks in advance.
Your code so far
function convertToRoman(num) {
// Note: Roman Numerals do not go above 3999
// Necessary numerals and array for creating the corresponding Roman Numeral
const romanNumerals = ['M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I'];
const arabicNumerals = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1];
let correspondingNumeral = [];
// finding the highest Roman numeral present in the number passed, and returning the appropriate index in arabicNumerals and romanNumerals
function findingBeginning(num) {
for (let i = 0; i < romanNumerals.length; i++) {
let char = num / arabicNumerals[i];
if (char >=1) {
let z = i;
console.log(z);
break;
}
}
return z;
}
// Calling the function
findingBeginning(num);
// Creating variables for the loop
let remainder = 0;
let char = 0;
// Acquiring the appropriate Roman Numerals
for (let i = z; i < romanNumerals.length; i++) {
// only for the first iteration
if (i == z) {
char = num / arabicNumerals[i];
remainder = num % arabicNumerals[i];
} else { // for all iterations afterwards
char = num % arabicNumerals[i - 1] // making char the remainder from the last iteration
check = char / arabicNumerals[i]; //making sure the current Roman Numeral is appropriate, and if not, moving to the next one down
if (check >= 1) {
continue;
} else {
break;
}
}
for (let p = 0; p < (char + 1); p++) {
correspondingNumeral.push(romanNumerals[i]);
}
}
// Construct string from correspondingNumeral and return it
}
convertToRoman(36);
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36
Challenge Information:
JavaScript Algorithms and Data Structures Projects - Roman Numeral Converter
