JavaScript: Someone knows the answer for this exercice?


#1

Hi, I would like to create a function that does the same that this three functions together using a for loop.

var x = "Write anything you want".split('').reverse().join('');
console.log(x);

So I wrote this one but doesn't work:

var reverseString = function (name) {
var string = " ";
for (var x = name.length-1; x > -1; x --);
return string = string += string[x];
};
console.log(reverseString("Write anything you want"));

I would apreciate any suggestion!


#2

Couple of errors in the code...

var string = " ";

It may not raise an exception, but string is not a good choice of variable name in the purist sense. String is a class of object, and string is a data type. Perhaps just use a shortened name, like str?

A for statement requires a code block. Yours has none, and in its place you have a semi-colon. That will always interrupt parsing of the statement and attempt to interpret just that line. Which will do nothing.

I've taken the liberty to revise your code. Study it and compare to yours to spot the differences.

var reverseString = function (text) {
    var str = "";
    for (var x = text.length; x > 0; x--){
        str += text[x-1];
    }
    return str;
};
console.log(reverseString("Write anything you want"));

// tnaw uoy gnihtyna etirW

#3

Wow! That was fast!
Thank you so much. Really appreciate it.
It was driving me crazy :slight_smile:


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.