0

currently, I am on a study binge for a couple of front-end job interviews. I do going through a bunch of problems, and I am currently stuck on a problem which is not hard at all but for some reason, I can't get it to work. Maybe you guys can take a look:

The question: Add a print function to the Array Prototype that prints all the contents in the array. ex. [1,2].print() -> 1,2

I wrote this function confidently, knowing it would work, but it didn't:

Array.prototype.print = () => {
 let str = ''
 for(let i = 0; i < this.length; i++) {
     this[i+1] === undefined ? str += this[i] : str += `${this[i]}, `
 }
 return str
}
console.log([1,2].print())

When I ran the function I got nothing in return. My thinking was this should have been tied with the array I was working on [1,2] but it's not. Its tied to the window.

Any idea what I did wrong? The help would be appreciated.

Best, Ayaz

Ayaz Uddin
  • 95
  • 2
  • 13
  • 4
    Don’t use the arrow function. – Mark Aug 20 '18 at 16:02
  • 3
    Arrow functions take the `this` of their enclosing context, in this case, `window`. Use a plain function using the `function` keyword instead of an arrow function. – CRice Aug 20 '18 at 16:02
  • gotcha thanks so much! – Ayaz Uddin Aug 20 '18 at 16:03
  • 2
    Possible duplicate of [When should I use Arrow functions in ECMAScript 6?](https://stackoverflow.com/questions/22939130/when-should-i-use-arrow-functions-in-ecmascript-6) – Andreas Aug 20 '18 at 16:04

2 Answers2

1

Using an arrow function binds the outer scope to this and not in the context of the Array.prototype

Array.prototype.print = function(){
  let str = '';
  let i = 0;
  let size = this.length;

  if(size === 1){
    return this[0];
  }

  for(; i < size; i++){
    str += this[i];
    
    if(size - 1 !== i){
      str += ',';
    }    
  }

  return str;
}

console.log([1].print())
console.log([1,2].print())
console.log([1,2,3].print())
dysfunc
  • 1,858
  • 1
  • 10
  • 13
1

Arrow functions don't get their own value for this. Instead of:

() => {

write:

function() {
wizzwizz4
  • 5,219
  • 2
  • 25
  • 49