0

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!

j08691
209k33 gold badges269 silver badges281 bronze badges
asked Feb 9, 2015 at 18:10
4
  • 5
    After the first return, you left the function. When you execute return the method is abandoned, nothing else is executed after that. Commented Feb 9, 2015 at 18:12
  • 1
    You need to look at what the return function does. That is kind of key to your issue. Commented Feb 9, 2015 at 18:13
  • 1
    Yeah your function returns in the first iteration so you would only get the last letter. You cannot have a return statement since it immediately exits the function. Save the answers in a variable and then after the for loop return the variable. Commented Feb 9, 2015 at 18:13
  • 2
    As you're learning, this how you'd generally do it -> "riyad".split('').reverse().join('') Commented Feb 9, 2015 at 18:14

2 Answers 2

1

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");

answered Feb 9, 2015 at 18:11
Sign up to request clarification or add additional context in comments.

2 Comments

Please don't encourage a beginner to use document.write(). While it might be useful for a test program, it is rarely what you want to use in a real web page for a variety of reasons.
@jfriend00 of course. Just wanted to so it in action. Thanks
1

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'));

answered Feb 9, 2015 at 18:24

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.