Change your console.log() to console.log(str). Then see what does the console say? The console should tell you what is happening as a result of your logic.
Also, you can’t change individual characters in a string using bracket notation.
right now you have console.log(str[i]). It’s not going to help you very much in terms of letting you know what’s happening. All it’ll tell you is what you pulled out of str[i].
Let me change a little and say that instead of replacing, just add console.log(str) below or above the log you already have.
you will need a new variable to hold the reversed string’s characters (can you guess what the variable type should be?). Then go through the given string , character by character, and assemble the new reversed string. This is just a hint so you have to investigate exactly what methods will work…
I think it should be an array. I declared the empty variable and then pushed string’s characters in it.
After that i googled for joining elements in array and i got join() method. It worked for me.
Am i approaching it right?
function reverseString(str) {
var reversed = ;
for(let i = str.length-1;i>=0;i–){
reversed.push(str[i]);
Great work in solving the problem. The concepts of algorithms are tough for most people - particularly when you’re learning a new language at the same time and trying to apply both!
Just a tip that could shorten your code (though the wording of the challenge makes me suspect its tests will fail if you take this approach) - the JavaScript language has a couple of built-in methods that complete some of your steps while writing less code:
I see you’ve already found .join(). You could also use .split() to create an array from a string and .reverse() to flip it.
Hi everyone this is my first post on the forums.
Once I pass the tests, I usually come here and see how my peers solved the challenge just to learn if there are better ways and so on. I enjoyed seeing your solutions to this challenge.
My solution to this challenge avoids using functions that we don’t have already seen on the curriculum. It uses a simple for loop that reads every single character in reverse order and then concatenates it to the string. Feel free to share your thoughts about my solution.
function reverseString(str) {
let rv = "";
for (let i = str.length - 1; i >= 0; i--) {
rv += str[i];
}
return rv;
}
your code is Good but the loop runs n times that is the length of the string.
we can write the solution where loop runs half the time of the length of the string.