JS Prototype and Iterables

HTML
CSS
C#
SQL

Prototype and Iterables

Prototypes

All JavaScript objects inherit properties and methods from a prototype.

A prototype is an object that is associated with every function and object by default in JavaScript, where the function’s prototype property is accessible and modifiable and the object’s prototype property (aka attribute) is not visible.

Every function includes a prototype object by default.

function Person(name, age){
  this.name = name;
  this.age = age;
}

Person.prototype.sayHello = function(){
  console.log(“Hello, my name is ” + this.name);
};

The prototype object is a special type of enumerable object to which additional properties can be attached to it which will be shared across all the instances of its constructor function.

So, use the prototype property of a function in the above example to have age properties across all the objects as shown below.

const john = new Person(“John”, 30);
const john = new Person(“John”, 30);

Every object which is created using literal syntax or constructor syntax with the new keyword includes __proto__ property that points to the prototype object of a function that created this object.

Iterables

Iterables in JavaScript allow you to loop over their elements using the for…of loop. The iterable protocol is implemented using the Symbol.iterator method. Here are some examples:

Iterating Over an Array:

for (const x of [1, 2, 3, 4, 5]) {
  console.log(x);
}

Iterating Over a String:

for (const char of “W3Schools”) {
  console.log(char);
}

Strings are also iterable, and the for…of the loop allows you to iterate over each character in the string.

JavaScript Iterators:

The iterator protocol is the mechanism by which objects are made iterable. An object becomes an iterator when it implements a next() method. The next() method should return an object with two properties:

– value: The next value in the iteration.
– done: A boolean indicating whether the iteration is complete (true if done, false otherwise).

Here’s an example of a simple iterator:

In this example, myIterable is an iterable object with a custom iterator. The iterator keeps track of the index and returns the next value in the sequence until the end is reached.

Iterables and iterators are fundamental concepts in JavaScript for working with sequences of values, making it easy to loop over elements in a consistent way.

Course Video