0

I was doing a JS exercise and it asked me to return a number combination in reversed order (1234 => 4321) so as always I tried do to it myself without looking for a solution and I came with:

function rev(n){
    for(i=n.length;i=0;i--){
       var reversed = reversed + n[i];
    }
    return reversed;
}
console.log(rev("test"));

But when I run this on VSCode it returns undefined to me and I do not understand which part of my code is wrong. Any ideas?

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
skr33t
  • 43
  • 5

5 Answers5

1

You define reversed in the for loop. What you need to do:

function rev(n) {
  let reversed = "";
  for (let i = n.length - 1; i >= 0; i--) {
    reversed = `${reversed}${n[i]}`;
  }
  return reversed;
}
console.log(rev("test"));
mplungjan
  • 169,008
  • 28
  • 173
  • 236
Alexandre Senges
  • 1,474
  • 1
  • 13
  • 22
  • Why should I use let? I've done the exact loop I am posting to calculate if a day was a Monday given the year and it worked without using let, I want to learn JavaScript from home but the answers of the exercises I am doing on w3resource are not by chance like your answers... I feel pretty stupid for not understanding your code – skr33t Mar 27 '20 at 13:37
  • You don't have to use `let` but it is almost always better than `var`. Explaining the difference here would be too long. You won't find many people using `var` nowadays so I advise you start using `let` if you plan on getting a job as a JS developer. [let vs var](https://stackoverflow.com/questions/762011/whats-the-difference-between-using-let-and-var) – Alexandre Senges Mar 27 '20 at 13:43
  • @mplungjan It wouldn't, it's supposed to be given a string :) – Alexandre Senges Mar 27 '20 at 13:51
  • `it asked me to return a number combination in reversed order (1234 => 4321) ` – mplungjan Mar 27 '20 at 13:54
  • @AlexandreSenges if you see my question I don't that I could work as a developer soon haha, but I'll read that. Where should I start learning JavaScript? Is there a better/faster way than doing +50 exercises on w3resources? They have pretty bad exercise answers + using old code. – skr33t Mar 27 '20 at 14:11
  • BTW, the part I did not understand was: `${reversed}${n[i]}` – skr33t Mar 27 '20 at 14:19
  • @skr33t you'll be surprised by how fast you can learn if you are determined. The way I started learning was by building my own project, I think that's a great approach because 1) it was something I was passionate about, so I kept motivated 2) You learn what really matters and not random stuff you find in exercises 3) It's something you can show and add on your resume right away :) . This syntax is called [template literals](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals), it allows you to easily insert the value of a variable inside of a string. – Alexandre Senges Mar 27 '20 at 14:38
  • @AlexandreSenges I have one project in mind because it does not exist at the moment but it is too much for me at the moment: a browser game with user registration for a 2vs2 game like poker with no currency involved and I planned on doing it with ReactJS, the problem is that I want it to be PoV (it is a traditional game and you communicate with winks) and my project would involve 3D work like three.js to be able to wink your teammate and to see your contender's wink maybe playing with PoV angles to make it more immersive, it only involves 36 cards on the deck and 3 cards per player. – skr33t Mar 27 '20 at 15:30
  • @skr33t I think you can start by making it 2D and just local multiplayer, then build on top of that – Alexandre Senges Mar 27 '20 at 17:20
1

Must you use loop?

Code below:

String(1234)  // make the number a string 
.split("")    // split on char making an array
.reverse()    // reverse that array
.join("")     // join it back

the + casts the reversed string back to number

console.log(
 +String(1234).split("").reverse().join("")
)
mplungjan
  • 169,008
  • 28
  • 173
  • 236
0

You can modify your existing code as the snippet below and it will work fine

function rev(str){
  var n = str.split("");
  var reversed ="";
    for(i=n.length-1; i >= 0 ; i--){
       reversed +=n[i];
    }
    return reversed;
}
console.log(rev("1234"));

Best way to reserve string

const reverseStr = str => {
  var splitString = str.split("");
  var reverseArray = splitString.reverse();
  var joinArray = reverseArray.join(""); 
  return joinArray;

};
Samuel
  • 368
  • 3
  • 12
0

you could do something like so:

const reverseString = text => {
  let result = "";
  for (let i = text.length - 1; i > -1; i--) {
    result += text[i];
  }

  return result;
};

console.log(reverseString('test'));
rcoro
  • 326
  • 6
  • 12
0

Okay, I understand your point. You intended to implement this and you wonder why your code is not working as expected. Kudos for your brave approach. Let's fix the issues you have step-by-step:

Initial code

function rev(n){
    for(i=n.length;i=0;i--){
       var reversed = reversed + n[i];
    }
    return reversed;
}
console.log(rev("test"));

Define reversed outside the loop

function rev(n){
    var reversed = "";
    for(i=n.length;i=0;i--){
        var reversed = reversed + n[i];
    }
    return reversed;
}
console.log(rev("test"));

Explanation: Your code recreated it inside your loop upon each step, and assuming it was not defined somehow outside the function it would crash upon the first use. You need to properly initialize it before you concatenate anything to it.

Fix the concatenation

function rev(n){
    var reversed = "";
    for(i=n.length;i=0;i--){
        reversed = reversed + n[i];
    }
    return reversed;
}
console.log(rev("test"));

Explanation: Removed the var keyword inside the loop, so you reuse reversed and correctly concatenate n[i] to it.

Properly define i

function rev(n){
    var reversed = "";
    for(let i = n.length - 1;i=0;i--){
        reversed = reversed + n[i];
    }
    return reversed;
}
console.log(rev("test"));

Explanation: You need to make sure that i exists as a variable. Also, we initialize it from n.length - 1, because indexing starts from 0, so the first element has the index of 0, the second element has the index of 1 and ... and the k'th element has the index of k-1, hence the last element of n is n.length - 1 and, as you have correctly figured out, the last element must be the first element.

Fix the continue condition

function rev(n){
    var reversed = "";
    for(let i = n.length - 1;i>=0;i--){
        reversed = reversed + n[i];
    }
    return reversed;
}
console.log(rev("test"));

Explanation: You assumed that the second statement inside the for is the end condition, but it is the exact opposite: it is the continue condition. It translates to plain words as "repeat as long as", instead of "repeat until".

Do it defensively

function rev(n){
    var reversed;
    if (typeof n === "string") {
        reversed = "";
        for(let i = n.length - 1;i>=0;i--){
            reversed = reversed + n[i];
        }
    }
    return reversed;
}
console.log(rev("test"));

Explanation: We only do the reversion if it's a string.

Let's support array:

function rev(n){
    var reversed;
    if (typeof n === "string") {
        reversed = "";
        for(let i = n.length - 1;i>=0;i--){
            reversed = reversed + n[i];
        }
    } else if (Array.isArray(n)) {
        reversed = [];
        for(let i = n.length - 1;i>=0;i--){
            reversed.push(n[i]);
        }
    }
    return reversed;
}
console.log(rev("test"));
console.log(rev(["t","e","s","t"]));

Explanation: The algorithm is similar for arrays as for strings, but we cope with technical differences nevertheless.

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175