Purpose of .prototype()

This is what FCC says:

Since numLegs will probably have the same value for all instances of Bird, you essentially have a duplicated variable numLegs inside each Bird instance.

This may not be an issue when there are only two instances, but imagine if there are millions of instances. That would be a lot of duplicated variables.

For this problem, I need to write Bird.prototype.numLegs() = 4. However, I thought the following code would eliminate the need to repeat yourself:

function Bird (name, color) {

this.name = name;

this.color = color;

this.feet = 2


var parrot = new Bird ('Bill', 'multi-colored')

var hawk = new Bird ('Death', 'black')

var blueJay = new Bird ('Tom', 'blue')

console.log(parrot) // -- > Bird { name: 'Bill', color: 'multi-colored', feet: 2}

console.log(hawk) // -- > Bird { name: 'Death', color: 'black', feet: 2}

console.log(blueJay) // -- > Bird { name: 'Tom', color: 'blue', feet: 2}

As you can see, I don’t have to repeat myself saying that I want every Bird to have 2 feet, since I didn’t give it a parameter. As FCC said though, is that in order not to repeat myself I’m going to need to use .prototype() to do this. Why is this the case? I didn’t have to repeat myself in that last section of code.

Using prototype is not meant to save lines of code but the computer’s memory.

In your example, every time you create a new instance of Bird it will have a new variable feet. So parrot, hawk and blueJay will have their own separate variable feet - 3 variables in total.

Whereas if you would use prototype, you would have only one variable inside Bird, and then each new instance would refer to that variable.

This is what it would look like:

Here’s this example and codepen, so you can play around with it. Use devtools rather than codepen’s console :wink: