Im getting the following errors:
-
str.fromCharCode is not a function
-
newStr.push is not a function
I have no clue why I’m getting those errors tbh. I might be using methods the wrong way
function rot13(str) {
var newStr = str;
for(i = 0; i < str.length; i++){
str.fromCharCode(str[i]-13);
newStr.push(i);
}
return newStr;
}
// Change the inputs below to test
rot13("SERR PBQR PNZC");
Link to the challenge:
https://www.freecodecamp.org/challenges/caesars-cipher
MDN is your best friend: (Check the syntax section - parameters and return values - I’ve looked each one up a thousand time, but the thousand-and-first time I used a function, I didn’t need to.)
1 Like
You just got answers on a similar problem.
Insert some console.log() into your function to practice some troubleshooting.
You can do console.log(str)
to find out if the parameter is being stored properly, then on each loop you can console.log(str[i])
to make sure you’re getting what you expect. The results will display in your browser developer tools console. open it with f12, or right click a page to open console.
1 Like
str.fromCharCode
is indeed not a function. String.fromCharCode(characterNumber)
is a method of String
.
Example:
String.fromCharCode(80); // returns 'P'
newStr.push()
is not a function because you cannot use push
on a string. .push()
is for an array. In your code you are passing a string to the function and using the variable str
within the function. When you assign var newStr = str;
your newStr
value is "SERR PBQR PNZC"
Remember that you need to shift the values for Caesars Cipher.
Consider this:
var character = "a"
var shiftedNumber;
shiftedNumber = character.charCodeAt() - 13; // 97 - 13
var newCharacter;
newCharacter = String.fromCharCode(shiftedNumber);
However, it may not be so straightforward. What happens when you have “A” and you do -13? Will it be a letter or some symbol or number? Something to keep in mind!
1 Like
Thank you so much for sharing your knowledge. Learning to code from scratch is a complicated task, but it gets easier due to people like you!
1 Like