novice programmer here, I'm trying an exercise where the objective is to print a string backwards. Here is my code:
function firstReverse(str) {
for(var i=str.length - 1; i >= 0;i --) {
return(str[i]);
}
};
firstReverse("riyad");
I keep getting the return of letter "d", but not the entire string. Not sure what is wrong here? Please help!
2 Answers 2
You could try this:
function firstReverse(str) {
for(var i=str.length - 1; i >= 0;i --) {
console.log(str[i]);
}
};
I keep getting the return of letter "d", but not the entire string
It is reasonable that you take this output, because the first time that your code steps into the for statement it will exit from it due to the return statement. In other words, you for statement will be executed only for the first step.
function firstReverse(str) {
for(var i=str.length - 1; i >= 0;i --) {
document.write(str[i]);
}
};
firstReverse("riyad");
The problem is, that return statement breaks your loop and returns the first letter it gets.
If you want to reverse a string - you may try to convert it to the Array, reverse it and concat elements of the new array back to string. I think its a simple solution. Here is a piece of code:
function reverse(str) {
return str.split('').reverse().join('');
}
console.log(reverse('abc'));
returnthe method is abandoned, nothing else is executed after that.returnfunction does. That is kind of key to your issue."riyad".split('').reverse().join('')