Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Manual: `Array.prototype.includes()` vs. `Array.includes()`

Incoming "noob" question:

Javascript has an includes method on arrays.

It looks like:

Array.includes()

But when I go to the Javascript Manual to understand this method, the heading on that page (for an appropriate technical reason, I realize) is:

Array.prototype.includes()

Similar things in the Javascript Manual have caused me to not like the manual at all (and alas, I rely on W3Schools more than the manual).

However, I really really want to learn to interpret the manual.

So, my question is: what's the significance of including the word .prototype in Array.prototype.includes() in the documentation, when the actual usage looks like: Array.includes()?

(Also, if anyone has suggestions on how I can improve my comprehension of the official Javascript Manual, I'd appreciate suggestions.)

like image 481
thanks_in_advance Avatar asked Apr 13 '26 20:04

thanks_in_advance


2 Answers

So, my question is: what's the significance of including the word .prototype in Array.prototype.includes() in the documentation, when the actual usage looks like: Array.includes()?

The significance is that actual usage doesn't look like Array.includes():

Array.includes();

That will throw a TypeError: Array.includes is not a function because Array.includes doesn't exist. Accessing a non-existing property evaluates to undefined, so Array.includes evaluates to undefined and thus Array.includes() is trying to call undefined as if were a function.

You can see that in action here:

console.log(Array.includes);

undefined();

The includes() method is defined on the prototype of the Array global object so that you can call it on instances of Array:

[].includes();

You can see that [].includes is a function:

console.log([].includes);

Compare this to Array.from which is defined on the Array constructor, not on the Array prototype:

console.log(Array.from);

You can use it like this:

console.log(Array.from({ length: 10 }, (_, num) => num << 2));
like image 101
Jörg W Mittag Avatar answered Apr 15 '26 11:04

Jörg W Mittag


If the documentation said Array.includes() you would literally type it like this (example):

Array.includes(1);

Instead it says Array.prototype.includes() which means it isn't called on the Array type itself, but on an instance of it. So in this case you would write:

const numbers = [1, 2, 3];
numbers.includes(1);
like image 28
Volper Avatar answered Apr 15 '26 11:04

Volper



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!