I was not able to understand why my code is not working Reverse a String

Tell us what’s happening:

Your code so far


function reverseString(str) {
  str.split('');
  str.reverse();
  str.join('');
  return str;
}

reverseString("hello");

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.75 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-algorithm-scripting/reverse-a-string

Try assigining the first line of code to a new variable

let splitStr=str.split(' ');

And then manipulate the array returned by split to reverse it.
You may also need to get rid of empty strings or trim the leading and trailing spaces in the string first.
If anything i am saying is hard to understand just google it. Eg. You can google how to trim a javascript string
Or google javascript string to see how it works (same goes for join and other functions you are trying)

1 Like

This method returns an array but does not change str. str is still the original string after that line of code. You will need to capture that return value in a variable.

1 Like

First, understand part of why this is not working, you should understand how values are passed in JavaScript and mutable vs. immutable data types.

Primitive data types (strings, booleans, numbers, null, undefined, and symbol) are passed by copy. They are immutable. This means that the only way to change their value is to reassign its value.

For example:

var str = 'HELLO';
str.toLowerCase();
console.log(str) // 'HELLO'

That’s not going to work. We’re calling a string method on str, but since strings are immutable, calling methods on them does not change the original string. If we wanted to make it so logging str will give us hello, we need to reassign strs value to be the return result of calling the toLowerCase method on it.

var str = 'HELLO'
str = str.toLowerCase();
console.log(str); // 'hello'

When dealing with objects, they are passed by reference and are mutable. Calling a method on an object can mutate (change) the object (which is often undesirable, actually).

Example:

var arr = [1, 2, 3];
arr.reverse();
console.log(arr); // [3, 2, 1]

You can see that even though we did not reassign arrs value, arr has been changed by the reverse method. (Note that not all array methods mutate! Many return brand new arrays, such as reduce, filter, map, and slice);

When you’re unsure whether or not a method mutates an object (arrays are objects), look the method up on MDN.

ETA: There’s also this great new site called Does It Mutate? that shows array methods and whether or not they mutate, as well as code examples.

1 Like

thanx now its working

Your solution works if you chain the methods

thanx
:grinning:
now my solution works