Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

How to write backwards an paragraph?

<!DOCTYPE html>
<html>
<head></head>
<body>
<p>Lorem ipsum dolor sit amet.</p>
<button onclick="abc()">Write the words backwards</button>
<p>Function abc() should sa rewrite the characters in the paragraph from above backwards (ex ".tema tis rol..."). Fix the code! :)</p>
<script>

    var x = document.getElementsByTagName('p')[0].innerHTML.split('');
    var total = x.length;

    function abc(){
        for(i = 0; i < total; i++){
            var y = [];
            y.push(x[i]);
        }
        document.getElementsByTagName('p')[0].innerHTML = y.join()
    }
</script>
</body>
</html>

fixed code formatting

Hi Deaconu,

The instructions imply there is some starter code. What was the starter code? Are there any functions you're not allowed to use?

1 Answer

Deaconu,

There are a few things you need to change. First your declaration of

var y = [];

needs to be moved up one line outside of the for loop, otherwise it gets overwritten with an empty array every time the for loop passes.

Next if you change

y.push(x[i]);

to

y.unshift(x[i]);

then it will reverse the string.

Alternatively you could keep it as push and reverse the for loop by changing it to

for (i = total - 1; i > -1; i--) {
    y.push(x[i]);
}

this will also reverse the string for you.

Lastly, just calling join() on array y will cause it to join with a comma as the separator, and your result will look like this... .,t,e,m,a, ,t,i,s, ,r,o,l,o,d, ,m,u,s,p,i, ,m,e,r,o,L which is clearly not what you are going for. To solve this, you can simply add a set of empty quotes into your join call making it

y.join("") or y.join('')

and then your result will be printed out .tema tis rolod muspi meroL as expected.

Happy coding!