Unshift not a function?

Tell us what’s happening:
Describe your issue in detail here.
Your code so far
.unshift not a function and same with push???


function reverseString(str) {
let reverse = [str];
let reversed = "";
for (let i = 0; i < str.length; i++){
 reversed.unshift(reverse[i])
}
return str;
}

reverseString("hello");
  **Your browser information:**

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

Challenge: Reverse a String

Link to the challenge:

unshift is a valid function on an array. What is the data type of reversed?

I used console.log(typeof(reversed)) it told me it was undefined.

1 Like

Your reversed is string. I don’t think there’s unshift for a string. reverse is the array.
Also,

let reverse = [str];

will create an array of one string str. You need to use a spread operator … if you want to break str into individual characters.

thanks I didn’t know you couldn’t unshift on a string

Strings are immutable in JS. This means you cant modify parts of them, instead, you must return a new variable copying a part, or assigned new value to the string variable you want to modify. You cant pick a position in a string and assign it a new value. This is opposite to arrays, which are a list of different values, which can be changed. Arrays and strings have different methods to be manipulated, there is only few which apply to both and unshift is not one of them. In order to utilize unshift, you will first need to convert the string into an array(and then construct a string back from the array, if its the value you want to return).

PS: to solve the challenge you can work with strings alone and not making use of arrays or their methods. You can simply start adding, one by one, the letters from the argument string to the reversed string, from back to start, only have to figure out a loop to do that.

1 Like

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