Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

147
Views
'this' keyword in array prototype function is undefined

I would like to write my own function for every array and I'm using the prototype keyword.

The problem is that when I created the following script:

Array.prototype.test = () => {console.log('length: ',this.length)};

const result = [1,2,3].test();

If I run it in the console of chrome I get the following result:

length:  0

If I run it on my local machine with node script.js I get the following result:

length:  undefined

Why is this.length different and why it doesn't reflect the length of the array I'm calling the function on?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

That's because you are using the arrow function syntax. The arrow function does not possess a this context, so it "points" to the global context.

The solution is simple:

Array.prototype.test = function() {console.log('length: ', this.length)};

const result = [1,2,3].test(); // length:  3

By adding explicitly function now your context (this) points to the object calling the function.

about 4 years ago · Juan Pablo Isaza Report

0

You are using an arrow function syntax.

When the "this" keyword are being called, it falls back into the global object.

In the browser it falls back into the window object and for this 😉 reason it's return 0 length.

But in the global node object, the length is undefined.

Instead, use the function keyword to get the Array.prototype context.

Array.prototype.test = function(){console.log('length: ',this.length)};
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!