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

152
Views
JavaScript: Get value inside Number prototype function

I try to use includes in prototype but it does not work but I do not get the expected results:

Number.prototype.inList = function (list) {
  return list.includes(this);
}

let value = 0;

let find1 = value.inList([0,1]);
let find2 = [0,1].includes(value);

console.log("find1", find1); // false
console.log("find2", find2); // true

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

0

Using Number#valueOf:

The valueOf() method returns the wrapped primitive value of a Number object.

Number.prototype.inList = function (list) {
  return list.includes(this.valueOf());
}

let value = 0;
console.log(value.inList([0,1]));

about 4 years ago · Juan Pablo Isaza Report

0

This happens in non strict mode, where compatibility requires that this is always an object, not a primitive. So in your case this is an instance of the Number constructor, and of course that object does not occur in your list.

In strict mode your code works, as this will be the primitive value (number)

Number.prototype.inList = function (list) {
  "use strict";
  return list.includes(this);
}

let value = 0;

let find1 = value.inList([0,1]);
let find2 = [0,1].includes(value);

console.log("find1", find1); // true
console.log("find2", find2); // true

Here the strict mode is only effective on the function -- and this is enough for this issue. If your script has no "legacy dependencies", you should better set it globally.

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!