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?
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:
function rev(n){
for(i=n.length;i=0;i--){
var reversed = reversed + n[i];
}
return reversed;
}
console.log(rev("test"));
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.
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.
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.
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".
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.
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.