Andrea Koutifaris
1 min readJul 23, 2018

--

Often interview questions are not just about algorithms, they are also used to see how the candidates reason.

In my opinion myArr.double() raises 3 points:

  • Algorithm
  • How to “attach” double function to an array
  • Well/Bad practices

Algorithm: With .push() you modify the array, with .concat() you do not. Instead of push, you can use also the for loop index: myArr[i+len] = myArr[i] .

“Attach” double function: you can alter the prototype (best answer to this question IMO), or you can attach the function to an existing array:
function enhanceArray(arr) { arr.double = function() {...};}

The first modify the Array.prototype, the second doesn’t.

Well/Bad practices: most important point IMO. Unless requirements ask differently, do not modify the input array and do not modify Array.prototype.

Why ? Have a look to the following example:

Array.prototype.double = function double() {
return this.concat(this);
}
const arr = [1];
for(let key in arr) {
console.log(arr[key]);
}
// Prints: 1
// ƒ double() {
// return this.concat(this);
//}

I understand the for ... in loop is not to be used to loop arrays, still there is a side effect few programmers know.

If you really want to modify the prototype of a native object, first have a look here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty

Don’t misunderstand me, this is not a criticism of what you wrote (which I found interesting), it is just my point of view on what they were really asking.

--

--

Andrea Koutifaris
Andrea Koutifaris

No responses yet