I have been going through some interviews lately and feel kinda dumb being asked technical questions on the spot. I actually felt really really dumb today after this particular one. So for those of you junior developers out there here is a tip.
This is what I said:
function reverseString(string){
var holder = new Array();
for(var i = string.length-1; i > -1; i--){
holder.push(string.length[i]);
}
return holder;
}
You would ONLY use this in a case when you are going to be doing something with the original string later in the same function. The more effective way would be to use this code:
function reverseString(string){
var swap = '';
var mid = Math.floor(string.length/2);
for(var i = 0; i < mid; i++){
swap = string[i];
string[i] = string[string.length - i];
string[string.length - i] = swap;
}
return string;
}
This function actually destroys the original string but that’s fine because if they need the string later they can store this call into a new variable like so:
var string = "foo";
var reversedString = reverseString(string);
This is where us developers need to look at the code and decide what is better: Faster code or more readable code?
A thank you to Ben for opening me up to a new way of thinking and for making me think about efficiency. 😀