Prototype and Iterables
Prototypes
A prototype is an object that every JavaScript object has, either directly or through inheritance. It defines properties and methods (functions) shared by all objects of the same type. It allows all objects to share common functionality without duplicating the same code.
In JavaScript, every object has an internal link to another object called its prototype. When you try to access a property or method on an object, JavaScript will first check if that property exists on the object itself. If it doesn’t, JavaScript will look for the property on the object’s prototype.
Adding Properties and Methods to Objects
Using the prototype Property
The JavaScript prototype property allows you to add new properties to object constructors
Example:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Prototypes</h2>
<p>The prototype property allows you to add new methods to objects constructors:</p>
<p id=”demo”></p>
<script>
function Person(first, last, age, eye) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eye;
}
Person.prototype.nationality = “English”;
const myFather = new Person(“John”, “Doe”, 50, “blue”);
document.getElementById(“demo”).innerHTML =
“The nationality of my father is ” + myFather.nationality;
</script>
</body>
</html>
Code explanation:
1. Constructor Function (Person):
function Person(first, last, age, eye) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eye;
}
Constructor Function: This function, Person, is used to create new Person objects.
o It takes 4 parameters: first, last, age, and eye, and assigns them to the properties of the object being created (i.e., this.firstName, this.lastName, this.age, and this.eyeColor).
o When you create a new Person object with this constructor, these properties are initialized based on the arguments passed.
2. Adding a New Property to All Instances Using Prototype:
Person.prototype.nationality = “English”;
Prototype: The prototype property is used to add new properties or methods to all instances created from the Person constructor.
o In this case, the nationality property is added to the Person prototype with the value “English”.
o This means all instances of Person (like myFather) will have the nationality property automatically set to “English”, without needing to explicitly set it in the constructor.
3. Creating a New Object (myFather):
const myFather = new Person(“John”, “Doe”, 50, “blue”);
Creating an Instance: A new Person object is created using the Person constructor, with the following values:
o firstName = “John”
o lastName = “Doe”
o age = 50
o eyeColor = “blue”
Since the nationality property was added to the Person prototype, this new myFather object will automatically inherit the nationality property with the value “English”.
4. Displaying the nationality Property:
document.getElementById(“demo”).innerHTML = “The nationality of my father is ” + myFather.nationality;
Displaying the Result: This line selects the HTML element with the id demo and sets its content to display the nationality property of the myFather object.
o The myFather object is automatically given the nationality property from the prototype, and it outputs: “The nationality of my father is English”.
Output:
The JavaScript prototype property also allows you to add new methods to object constructors:
Example:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Prototypes</h2>
<p id=”demo”></p>
<script>
function Person(first, last, age, eye) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eye;
}
Person.prototype.name = function() {
return this.firstName + ” ” + this.lastName
};
const myFather = new Person(“John”, “Doe”, 50, “blue”);
document.getElementById(“demo”).innerHTML =
“My father is ” + myFather.name();
</script>
</body>
</html>
Code explanation:
1. Constructor Function (Person):
function Person(first, last, age, eye) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eye;
}
Constructor Function: This function, Person, is used to create new Person objects with the following properties:
o firstName, lastName, age, and eyeColor are initialized using the parameters passed to the constructor.
• How it works: When a new Person object is created using this constructor, it will have the firstName, lastName, age, and eyeColor properties set to the values passed during creation.
2. Adding a Method to the Prototype:
Person.prototype.name = function() {
return this.firstName + ” ” + this.lastName;
};
Prototype Method: Here, a method called name is added to the Person prototype. This method:
o Returns the full name by concatenating firstName and lastName properties of the object.
o This method can now be accessed by any object created using the Person constructor, including myFather.
• Why Use prototype: By adding the name method to the prototype, you avoid duplicating the method for every instance of Person. It is shared across all instances.
3. Creating a New Object (myFather)
const myFather = new Person(“John”, “Doe”, 50, “blue”);
Creating an Instance: A new object myFather is created from the Person constructor with the following values:
o firstName = “John”
o lastName = “Doe”
o age = 50
o eyeColor = “blue”
• The myFather object now has access to the name method, which was added to the prototype of Person.
4. Calling the name Method:
document.getElementById(“demo”).innerHTML = “My father is ” + myFather.name();
• Calling the name Method: The name method is called on the myFather object. This method concatenates firstName and lastName of myFather and returns the full name: “John Doe”.
• The result is then displayed inside the HTML element with the id=”demo”.
Output:
Iterables
An iterable is a special type of object that allows you to loop over its elements individually. Think of it like a list of items, such as a collection of toys. An iterable is a collection where you can go through each item in the list, one by one, just like flipping through the pages of a book.
Some built-in objects, such as arrays, strings, and maps, are iterable in JavaScript. They allow you to use looping mechanisms like for…of to access each item.
The For Of Loop
The JavaScript for..of statement loops through the elements of an iterable object.
Syntax:
for (variable of iterable) {
// code block to be executed
}
Iterating
Iterating is easy to understand.
It simply means looping over a sequence of elements.
Here are some easy examples:
• Iterating over a String
• Iterating over an Array
The For Of Loop
You can use a for..of the loop to iterate over the elements of a string:
Example:
<body>
<script>
const name = “IqraTech”;
for (const x of name) {
console.log(x);
}
</script>
</body>
Code explanation:
const name = “IqraTech”;
This line creates a constant variable name and assigns it the string value “IqraTech”. Strings in JavaScript are iterable, meaning you can loop through each character in the string.
for (const x of name) { … }
The for…of the loop is used to iterate over the iterable object. In this case, the iterable object is the string name.
const x defines a new variable x for each iteration of the loop. During each iteration, x takes the value of the next character in the string “IqraTech”.
The loop will execute once for each character in the string.
console.log(x);
This line prints the current value of x (which represents a character from the string) to the console.
So, in this case, it will print each character of the string “IqraTech” one by one:
• I
• q
• r
• a
• T
• e
• c
• h
Output:
Iterating Over an Array
You can use a for..of the loop to iterate over the elements of an Array:
Example:
<body>
<script>
const letters = [“a”,”b”,”c”];
for (const x of letters) {
console.log(x);
}
</script>
</body>
Code explanation:
const letters = [“a”,”b”,”c”];
Here, we are creating a constant variable letter that holds an array with three elements: “a”, “b”, and “c”. Arrays in JavaScript are iterable, meaning they can be looped through.
for (const x of letters) { … }
The for…of the loop is being used to iterate over each element in the letters array.
In each iteration, the variable x will take the value of the next element in the array.
For example, in the first iteration, x will be “a”, in the second iteration, x will be “b”, and in the third, x will be “c”.
This loop will run once for each element in the array.
console.log(x);
Inside the loop, console.log(x) will print the current value of x to the console.
So, for each iteration, the value of x (which corresponds to an element in the letters array) will be printed on a new line.
Output:
JavaScript Iterators
In JavaScript, an object is considered an iterable if it implements the Symbol.iterator method. This method returns an iterator, which knows how to step through the collection of items.
Example of an Iterable Object:
<body>
<script>
let candies = {
items: [‘chocolate’, ‘lollipop’, ‘gummy bear’],
// The Symbol.iterator method
[Symbol.iterator]: function() {
let index = 0;
let items = this.items;
return {
next: function() {
if (index < items.length) {
return { value: items[index++], done: false };
} else {
return { value: undefined, done: true };
}
}
};
}
};
// Using the iterable object
for (let candy of candies) {
console.log(candy)
; // Outputs: chocolate, lollipop, gummy bear
}
</script>
</body>
Code explanation:
1. The candies Object:
let candies = { items: [‘chocolate’, ‘lollipop’, ‘gummy bear’], };
This object, candies, has a property called items, which is an array containing a list of candies: ‘chocolate’, ‘lollipop’, and ‘gummy bear’.
2. Implementing the Symbol.iterator Method:
[Symbol.iterator]: function() { let index = 0; let items = this.items; return { next: function() { if (index < items.length) { return { value: items[index++], done: false }; } else { return { value: undefined, done: true }; } } }; }
[Symbol.iterator]: This defines the iterator method for the candies object. By adding this method, the object becomes iterable.
Inside the method:
• let index = 0;: Initializes an index to keep track of the current position in the items array.
• let items = this.items;: Stores the array of items ([‘chocolate’, ‘lollipop’, ‘gummy bear’]).
The method returns an iterator object with a next() function:
• next(): This function will be called every time the for…of loop iterates over the object.
• If the index is less than the length of the items array, the function returns an object with two properties:
• value: The current candy item (items[index++]).
• done: false, indicating the iteration is not yet complete.
• If the index is equal to or greater than the array length, the function returns:
• value: undefined: No value to return.
• done: true: The iteration is complete.
3. The for…of Loop:
for (let candy of candies) { console.log(candy); }
The for…of loop automatically calls the Symbol.iterator method to get the iterator object.
The loop keeps calling the next() method of the iterator until done is true.
Output:
Course Video
YouTube Reference :
1) ES6 – Iterables & Iterators || JavaScript || Hindi || Coding Scenes
2) Magic of Prototype in javascript | chai aur #javascript in Hindi
3) JavaScript Tutorial | JavaScript Iterators in English
4) Understanding Iterable in JavaScript in English
5) Visually Understanding JavaScript Prototypes in English
A prototype is an object associated with every JavaScript function and object by default. It allows you to add methods and properties that all instances of the object can share. Learn more in our JavaScript prototype and iterables free course video.
Use the prototype property to define shared methods.
Example:
function Person(name) {
this.name = name;
}
Person.prototype.greet = function() {
console.log(`Hello, my name is ${this.name}`);
};
Explore this in the JS prototype and iterables with free video tutorial.
Iterables are objects that can be iterated over, such as arrays, strings, maps, and sets. They implement the Symbol.iterator method. Find detailed explanations in the Free JavaScript prototype and iterables tutorial for beginners.
The for…of loop iterates over the values of iterable objects.
Example:
let numbers = [1, 2, 3];
for (let num of numbers) {
console.log(num);
}
Check this out in the JavaScript prototype and iterables with free tutorial.
- for…in: Iterates over the keys of an object.
- for…of: Iterates over the values of an iterable object.
Learn the differences in our JavaScript prototype and iterables free course video.
The Symbol.iterator method defines how an object should be iterated. Custom objects can implement this to make them iterable. See practical examples in the JS prototype and iterables with free video tutorial.
Implement the Symbol.iterator method on the object.
Example:
let iterableObj = {
*[Symbol.iterator]() {
yield 1;
yield 2;
yield 3;
}
};
for (let value of iterableObj) {
console.log(value);
}
Watch this demonstrated in the Free JavaScript prototype and iterables tutorial for beginners.
Generator functions return iterators and allow you to pause and resume execution using the yield keyword. Learn this concept in the JavaScript prototype and iterables with free tutorial.
The prototype chain is a hierarchy of objects that JavaScript uses to resolve properties and methods. If an object doesn’t have a property, it looks up the chain to its prototype. Find more about this in the JavaScript prototype and iterables free course video.
Common methods include:
- Object.create()
- Object.getPrototypeOf()
- Object.setPrototypeOf()
Explore these methods in the JS prototype and iterables with free video tutorial.