close icon
daily.dev platform

Discover more from daily.dev

Personalized news feed, dev communities and search, much better than what’s out there. Maybe ;)

Start reading - Free forever
Start reading - Free forever
Continue reading >

Understanding Prototype Array in JavaScript

Understanding Prototype Array in JavaScript
Author
Nimrod Kramer
Related tags on daily.dev
toc
Table of contents
arrow-down

🎯

Learn about the concept of prototype arrays in JavaScript and how to work with them efficiently. Understand prototypal inheritance, customize Array.prototype, and consider performance implications.

Understanding how the prototype array in JavaScript works can significantly enhance your coding skills, allowing you to perform complex operations with arrays more efficiently. Here’s a quick overview:

  • Prototypes in JavaScript enable objects to inherit properties and methods. Arrays use this to access a wide range of methods like map(), filter(), and reduce().
  • Prototypal Inheritance means if an object lacks a property or method, it checks its prototype as part of a chain until it finds what it needs.
  • Customizing Array.prototype lets you add your own methods to all arrays, making it possible to extend the functionality of arrays globally.
  • Performance Considerations are crucial when adding methods to Array.prototype to avoid potential slowdowns in your applications.

This guide will walk you through the concept of prototype arrays, how to work with them, and the implications of extending array functionalities in JavaScript.

What are Prototypes?

In JavaScript, objects have a special link called [[Prototype]] that points to another object, the prototype. When you ask for a property that the object doesn’t have, JavaScript looks at the prototype to find it. This keeps going until the property is found or there are no more prototypes to check.

Here are some key points:

  • Every JavaScript object gets its properties and methods from a prototype.
  • The very top prototype is Object.prototype.
  • Things like Array and Date build off Object.prototype. So, if you make an array or date, it gets stuff from those prototypes too.
  • You can add new methods to prototypes. This means all objects made from that prototype will have those new methods.

Prototypal Inheritance

This is a fancy way of saying that if an object doesn’t have what it needs, it asks its prototype. This can go on until it finds what it needs or runs out of prototypes to ask. For example, if you make an object from another object, it can use all the stuff from the first object plus its own stuff.

Here’s a simple example:

let foo = {
  name: 'foo',
  log: function() {
    console.log(this.name); 
  }
}

let myObject = Object.create(foo); 

myObject.log(); // 'foo'

By using Object.create(), myObject gets everything from foo.

Working with Prototypes

Here's how you can use prototypes:

Add methods to built-in objects:

Array.prototype.shuffle = function() {
  // How to shuffle
};

let arr = [1, 2, 3];
arr.shuffle(); 

Share methods across objects:

let utils = {
  calculateTip() { /*...*/ } 
};

let restaurantBill = Object.create(utils);
restaurantBill.calculateTip(); 

Make one object type act like another:

function Vehicle(type) {
  this.type = type;
}

Vehicle.prototype.drive = function() {
  console.log('Driving a ' + this.type);
};

function Car() {
  Vehicle.call(this, 'car');
}

Car.prototype = Object.create(Vehicle.prototype);

let car = new Car();
car.drive(); // Logs "Driving a car"

Getting the hang of prototypes means you can make your code do more with less effort. It’s all about sharing and reusing code in smart ways.

The Array Prototype in JavaScript

Think of Array.prototype in JavaScript as a big tool kit that all arrays can use. It's like a shared backpack of tools that any array you make automatically gets to dip into.

What is Array.prototype?

Array.prototype is basically a big collection of tools and shortcuts that every array in JavaScript gets from the start. So, when you create a new array like this:

let myArray = [];

It already knows how to do things like sorting, searching, and changing because it has Array.prototype backing it up.

Some tools it comes with include:

  • map()
  • filter()
  • reduce()
  • find()
  • some()

This means you can use these tools right away on any array without extra work.

Why Array.prototype Matters

Getting to know Array.prototype can really up your game with arrays. Here’s why it's cool:

  • Add your own shortcuts - You can add new methods to Array.prototype so every array can use them:
Array.prototype.shuffle = function() {
  // how to mix up the array
};

Now, every array has a shuffle() method.

  • Understand arrays better - When you use a method like arr.filter(), it's actually Array.prototype.filter() doing the work. Knowing this helps you get how arrays tick.
  • Change how built-in tools work - You can tweak how the built-in methods act for all arrays. It's usually not the best idea, but it's possible.

So, learning about Array.prototype gives you more power over arrays, one of the most common tools in coding.

Array.prototype and Array Behavior

When you do something like:

let arr = [1, 2, 3]; 

arr.push(4);
arr.slice(0, 2); 

The array arr doesn't have push or slice built into it. It gets these abilities from Array.prototype.

Here’s a step-by-step of what happens:

  • You try arr.push(4).
  • The array arr checks if it knows how to push, and since it doesn't, it asks Array.prototype.
  • Array.prototype has push, so it helps arr out.
  • arr now has a new item added to it.

This is how arrays can do a lot without you having to program everything from scratch. By understanding and using Array.prototype, you can make arrays do even more cool stuff.

Common Methods of Array.prototype

Array.prototype has a bunch of handy methods that help you work with arrays better. Here's a quick look at some of the most important ones.

Iteration Methods

These methods help you go through each item in an array and do something with it.

  • forEach() - Runs a function for each item in the array. It's great for when you want to do something like logging each item:
let arr = [1, 2, 3];

arr.forEach(el => {
  console.log(el); 
});
// Prints 1, 2, 3
  • map() - Creates a new array by applying a function to each item in the original array:
let arr = [1, 2, 3];

let doubled = arr.map(el => el * 2); 

console.log(doubled); // [2, 4, 6]  
  • filter() - Makes a new array with only the items that meet a certain condition:
let arr = [1, 2, 3]; 

let biggerThanOne = arr.filter(el => el > 1);

console.log(biggerThanOne); // [2, 3]
  • reduce() - Turns all the items in an array into a single value. It adds up each item using a function you provide:
let arr = [1, 2, 3];

let total = arr.reduce((sum, el) => sum + el, 0); 

console.log(total); // 6

Accessor Methods

These methods let you look at array items without changing the array:

  • join() - Puts all the array items together into one string:
let arr = [1, 2, 3];

arr.join('-'); // '1-2-3'
  • slice() - Gives you a new array with just a part of the original array:
let arr = [1, 2, 3, 4]; 

arr.slice(1, 3); // [2, 3]
  • indexOf() - Finds the first place where a certain item appears in the array, or -1 if it's not there:
let arr = [1, 2, 3];

arr.indexOf(2); // 1

Mutator Methods

These methods change the original array:

  • push() / pop() - Lets you add or remove items from the end of the array:
let arr = [1, 2];

arr.push(3); // arr is now [1, 2, 3]  

arr.pop(); // arr is back to [1, 2]
  • unshift() / shift() - Lets you add or remove items from the start of the array

  • splice() - Lets you add or take out items anywhere in the array

Customizing Array.prototype

When you want to add your own tools to arrays in JavaScript, you can, but you should be careful. Here's a guide on how to do it right.

Extending Built-In Objects

Before you add new tools to arrays, remember to:

  • Make sure the tool name you want to add isn't already used to avoid mix-ups.
  • Create tools that any array can use, not just one specific kind.
  • Aim to return a new array instead of changing the original one.
  • Explain clearly what your new tool does.

It's generally not a good idea to change the basic array tools directly. A safer way is to use a wrapper:

// Add to a wrapper object 
Object.extend(Array, {
  shuffle() {
    // How to mix up the array
  } 
});

// How to use it
let arr = [1, 2, 3];
Array.shuffle(arr);

Adding Custom Methods

Here are some custom array tools you might find useful:

// Remove repeats
Array.prototype.unique = function() {
  return this.filter((el, index, array) => array.indexOf(el) === index);
}

// Pick a random item
Array.prototype.sample = function() { 
  return this[Math.floor(Math.random() * this.length)];
}

// Mix up the order
Array.prototype.shuffle = function() {
  // How to shuffle
}

To use a tool like unique():

let names = ['John', 'Sarah', 'Mike', 'Sarah']; 

let uniqueNames = names.unique(); // ['John', 'Sarah', 'Mike']

Considerations & Warnings

Changing Array.prototype affects all arrays everywhere, so be cautious. Also, remember some tools like sort() and reverse() are already there.

Keep in mind:

  • Avoid changing the basic tools for JavaScript types.
  • There might be conflicts with other code.
  • It can be tricky to figure out problems.

In short, adding your own tools to arrays can be useful but should be done thoughtfully. Think about using wrappers or classes for a cleaner approach.

Prototype Chain and Array Inheritance

Visualizing the Prototype Chain

Imagine you create an array in JavaScript. This array doesn't just stand alone; it's connected to a bigger family that gives it special powers. Here's how it looks:

myArray ---> Array.prototype ---> Object.prototype ---> null
  • myArray is your array.
  • It gets its powers from Array.prototype.
  • Array.prototype gets its powers from Object.prototype.
  • At the very end, there's null, meaning no more connections.

So, when you use a method like myArray.map(), the system checks myArray, then Array.prototype, and keeps going up the chain until it finds map().

You can peek into this family tree using __proto__:

let arr = [];

console.log(arr.__proto__ === Array.prototype); // true

console.log(arr.__proto__.__proto__ === Object.prototype); // true  

Or see what powers (properties) you've inherited:

let arr = [];

// Comes from Array.prototype
console.log(arr.length); 

// Comes from Object.prototype
console.log(arr.hasOwnProperty('length'));  

Understanding this tree helps you see all the cool stuff arrays can do.

Implications for Arrays

Here's why this family tree matters for arrays:

  • Arrays can use awesome methods like map(), filter(), slice(), and more.
  • You can add your own methods to Array.prototype to give all arrays new abilities.
  • Arrays also get basic object methods like hasOwnProperty() and toString().
  • The way arrays look up these methods is super efficient, thanks to this family tree.

In short, Array.prototype is like a treasure chest for arrays. Knowing how it works lets you do more cool stuff with arrays, using less effort.

sbb-itb-bfaad5b

Practical Applications and Examples

Iterating Collections

Array methods like map(), filter(), and reduce() are super handy for changing array data. Here's how you might use them:

// Double all numbers
let numbers = [1, 2, 3];
let doubled = numbers.map(n => n * 2); // [2, 4, 6]

// Keep only the odd numbers
let nums = [1, 2, 3, 4]; 
let odds = nums.filter(n => n % 2 !== 0); // [1, 3]

// Add all numbers together
let sum = nums.reduce((acc, n) => acc + n, 0); // 10

These methods let you loop through arrays and change them without having to write a lot of repetitive code.

Shared Utility Functions

You can add your own methods to all arrays. Here are some examples:

// Remove duplicate elements
Array.prototype.unique = function() {
  return this.filter((el, i, arr) => arr.indexOf(el) === i);
};

// Pick a random element
Array.prototype.sample = function() {
  return this[Math.floor(Math.random() * this.length)]; 
};

// Mix up the order
Array.prototype.shuffle = function() {
  // shuffle algorithm
};

Now, every array can use these new methods:

let arr = [1, 2, 2, 3];

arr.unique(); // [1, 2, 3]  

[1, 2, 3].sample(); // Random element

This makes it easy to reuse code in different projects.

Polyfilling Features

Some newer array methods might not work in older browsers. You can fix this by adding the missing methods yourself:

if (!Array.prototype.find) {
  Array.prototype.find = function(callback) {
    // Implementation
  };
}

Now, .find() will work everywhere, letting you use new JavaScript features in any browser.

Advanced Topics

Array.prototype.with()

The with() method lets you run a function with a specific this value and arguments. It's like saying, 'Hey, I want this function to think this is something else for a bit.'

Here's how you write it:

arr.with(callback[, thisArg])

callback is the function you want to run, and thisArg tells the function what this should be during that run.

For example:

let arr = [1, 2, 3];

arr.with(function() {
  console.log(this); 
}, 'hello'); // Shows 'hello'

In the callback function, this points to 'hello' instead of the array.

with() is handy if you want to use a function for one thing on something else without changing the original function.

It's like a safe space to try out the function with different settings. And it doesn't change the original array.

Why is Array.prototype an Array?

You might find it weird that Array.prototype is an array itself!

console.log(Array.isArray(Array.prototype)); // true

This means you can use array methods right on Array.prototype. For example:

Array.prototype.map(x => x * 2); // [], and it works fine

If Array.prototype was just a regular object, doing this would cause an error.

Having it as an array makes things consistent. Since arrays come from Array.prototype, it being an array too just fits.

This setup avoids strange errors and lets you use Array.prototype like any other array in some cases.

It makes dealing with arrays and prototypes in JavaScript a bit easier.

Performance Considerations

When you add your own methods to Array.prototype, think about how it affects speed:

  • Keep functions simple - Complex stuff can slow things down.
  • Stay away from closures - They make new functions each time you call them.
  • Stop early if you can - This avoids doing extra work.
  • Check your code's speed - Look for slow spots.
  • Be careful with changes - Only add to Array.prototype when really needed.

Also, try to use the built-in methods instead of making your own:

// This is quicker than making your own find method
arr.includes(item); 

// This is quicker than making your own way to filter
arr.every(fn);

The built-in methods are super fast - use them when you can!

In short, be mindful when adding to Array.prototype. It can slow things down if not done right. Always test and look for ways to make things faster.

Conclusion

Understanding how Array.prototype works is crucial for getting the most out of arrays in JavaScript. Let's go over the key points again:

  • Think of Array.prototype as a big tool kit that arrays can use to do more things. This is because of something called prototypal inheritance. When an array needs a method it doesn't have, it borrows it from this tool kit.
  • Learning about common methods like .map(), .filter(), and .reduce() is really helpful. They let you go through, search, and change array data in smart ways.
  • You can add your own methods to Array.prototype. This means all arrays can use these new methods, making it easier to share useful functions across your coding projects.
  • Understanding the prototype chain - how arrays get their methods from Array.prototype and other object prototypes - helps you see where all these handy array methods come from.
  • When adding your own methods to Array.prototype, remember to keep things simple to avoid slowing things down.

In short, getting to know how prototypes and arrays work together is super important for writing good, efficient JavaScript code. Once you get the hang of using array methods, you'll save a lot of time and be able to do more advanced stuff. So, take some time to really understand Array.prototype and improve how you work with arrays!

Further Reading & Resources

If you're keen to dive deeper into the world of prototypes and arrays in JavaScript, here are some handy places to check out:

  • Object.prototype on MDN - This page talks about the basic prototype that other prototypes get their features from.
  • Working with Objects on MDN - A helpful guide on using objects and prototypes in JavaScript, making these concepts easier to grasp.
  • Inheritance and the prototype chain on MDN - A clear explanation of how prototypes link together and how objects inherit features in JavaScript.
  • Array on MDN - Detailed info on all the array methods available, helping you understand how to work with arrays effectively.
  • Extending Built-in Objects in JavaScript - Discusses the dos and don'ts of adding your own features to JavaScript's built-in objects, like arrays.
  • Array Explorer - A fun, interactive tool that shows you what different array methods do, making it easier to learn about them.

These resources are great for getting a better handle on JavaScript's prototype system and how to do more with arrays. They offer lots of examples and are a good way to learn by doing.

What is prototype in array in JavaScript?

In JavaScript, arrays have a special feature called a prototype. This lets you add new ways to work with arrays, like adding items or taking them out. When you create an array, it automatically gets these abilities from something called Array.prototype. This means you can use handy tools like push() and pop() without setting them up yourself.

How does prototype work in JavaScript?

In JavaScript, every object comes with a hidden link to another object, known as its prototype. This prototype is also an object and has its own prototype, creating a chain. This chain keeps going until there's a prototype with no further link (null). This setup helps objects inherit features from one another.

How prototype chain works in JavaScript?

Objects in JavaScript have a special link to their prototype, which is another object. This linking forms a chain where each prototype points to another prototype, and this goes on until there's an end point with null. This chain is how JavaScript objects share features and properties.

How to use __proto__ in JavaScript?

The __proto__ property lets you see or set the prototype of an object. You can use it to check an object's prototype or even set it when you're creating an object. This is a way to directly work with the prototype chain, but it's generally recommended to use methods like Object.create() for setting prototypes when making new objects.

Related posts

Why not level up your reading with

Stay up-to-date with the latest developer news every time you open a new tab.

Read more