Hi, I have been trying to complete this challenge for 2 hours and I’ve ended up with a code that seems to work as per console logs but doesn’t pass the tests.
I believe this is a bug but if something is wrong with this code, I will be happy for any pointers!
let str = ''
var result = ''
var asc = 0;
var codes = [ ];
//start
function rot13(str) {
str = str.toUpperCase();
var arr = str.split("");
for (let i=0; i < arr.length; i++) {
var asc = arr[i].codePointAt(0);
codes.push(asc);
}
//console.log(codes);
for (let j=0; j < codes.length; j++) {
if (codes[j] >= 65 && codes[j] <= 90) {
if (codes[j] < 78) {
codes[j] = codes[j] + 13;
} else {
codes [j] = codes [j] - 13;
}
} else {
codes[j] = codes[j];
}
}
//console.log(codes);
for (let m=0; m < codes.length; m++) {
codes[m] = String.fromCharCode(codes[m]);
}
result = codes.join('');
console.log(result);
return result;
}
rot13("SERR CVMMN!");
Next time please provide a link to the challenge.
I had to copy you code and look it up in the curriculum myself to test out what’s going on - not everyone is going to do that
In short: You have to place the first four lines (where you declare a bunch of variables) INSIDE your function.
This is good practice because you should always avoid global variables.
Can’t tell you why exactly this is causing the failure.
Your code contains global variables that are changed each time the function is run. This means that after each test completes, subsequent tests start with the previous value. To fix this, make sure your function doesn’t change any global variables, and declare/assign variables within the function if they need to be changed.
Example:
var myGlobal = [1];
function returnGlobal(arg) {
myGlobal.push(arg);
return myGlobal;
} // unreliable - array gets longer each time the function is run
function returnLocal(arg) {
var myLocal = [1];
myLocal.push(arg);
return myLocal;
} // reliable - always returns an array of length 2
I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.
You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.