avatarKirti K

Summary

The provided content is a comprehensive guide for beginners on mastering JavaScript basics, particularly focusing on prototyping, as part of a 100-day interview preparation journey.

Abstract

The web content outlines "Day 2" of a 100-day JavaScript interview preparation series, with a focus on understanding prototyping in JavaScript. It provides clear explanations, illustrative code examples, and step-by-step guidance on defining prototypes, creating constructor functions, and inheriting properties and methods. The guide emphasizes the importance of prototypes for sharing behavior among objects and includes practical examples to demonstrate how to add methods to prototypes, create instances, and access prototype methods. It also addresses common interview questions related to JavaScript prototyping, such as the difference between setting properties directly on an object versus on its prototype, checking if an object inherits a property, creating constructor functions with prototypes, and understanding the impact of modifying properties on an object's prototype. The content aims to solidify foundational JavaScript knowledge and prepare readers for technical interviews.

Opinions

  • The author, Kirti Kaushal, believes in the importance of a structured learning journey, as evidenced by the 100-day plan for interview preparation.
  • The author emphasizes that understanding prototypes is crucial for demonstrating proficiency in JavaScript during interviews.
  • There is an opinion that sharing knowledge is a key part of the learning process, as indicated by the encouragement to share, clap, and follow to support the author's work.
  • The author values practical application and encourages readers to try out the concepts by providing code samples and suggesting exercises.
  • The content reflects a positive and motivational tone, with phrases like "Happy learning" and "Kind is cool," suggesting the author's commitment to a supportive learning environment.
  • The author's experience is highlighted as a resource for readers, with an invitation to subscribe and follow on GitHub for further learning opportunities.

JavaScript Day 2— Mastering JavaScript Basics: A Comprehensive Guide for Interview Preparation

100 Days of JavaScript Interview Prep: A Beginner’s Journey

DAY 2(March 24, 2024) — Prototyping in JavaScript and how we can explain with possible examples | Kirti Kaushal

Welcome to Day 2 –100 Days of JavaScript Interview Prep: A Beginner’s Journey

Each concept is explained in clear, easy-to-understand language, accompanied by illustrative code examples to reinforce learning.

Get ready to ace your next JavaScript interview with this comprehensive guide! Join us as we document a 100-day adventure filled with learning, practice, and growth.

DAY 2(March 24, 2024) — Prototyping in JavaScript and how we can explain with possible examples

Before we start Prototyping questioning let’s first start to understand the Prototyping in JavaScript with simple example.

Prototyping in JavaScript allows you to add new properties and methods to existing objects.

Here’s a step-by-step guide to defining prototypes in JavaScript:

Step 1. Create a Constructor Function:

How to define Constructor function

Define a constructor function for the type of objects you want to create.

For example:

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

Step 2. Add Methods to the Prototype:

How to add Method of above Person Constructor

Extend the prototype of the constructor function by adding methods that will be shared among all instances of the object.

For example:

Person.prototype.greet = function(){
 return "Hello, my name is " + this.name + " and I'm " + this.age + " years old.";
}

Step 3. Create Instances:

How to create Instances in above Person

Instantiate objects using the constructor function. The instances will inherit the properties and methods defined in the prototype.

For example:

var person1 = new Person("Ana", 30);
var person2 = new Person("Soni", 25);

Step 4. Access Prototype Methods:

How to access Method

You can now call the prototype methods on the instances of the object.

For example:

console.log(person1.greet()); 
// Output: Hello, my name is Ana and I'm 30 years old.
console.log(person2.greet()); 
// Output: Hello, my name is Soni and I'm 25 years old.

By following these steps, We can effectively define prototypes in JavaScript to share properties and methods among objects of the same type.

Let’s now start all related questioning about Prototyping

Question 1

Explain the difference between setting a property directly on an object versus setting it on the object’s prototype in JavaScript.

Answer :

When setting a property directly on an object, that property exists only for that specific instance of the object.

However, when setting a property on the object’s prototype, that property becomes accessible to all instances of that object type, including those created before the property was added to the prototype.

// Step 1: Define a constructor function
function Person(name) {
  this.name = name;
}
// Step 2: Create an instance of Person
var person1 = new Person("Alice");
// Step 3: Set a property directly on the object
person1.age = 30;
// Step 4: Create another instance of Person
var person2 = new Person("Bob");

// Step 5: Access the age property
console.log(person1.age); // Output: 30
console.log(person2.age); // Output: undefined

In this example, the age property is set directly on person1, so it exists only for person1 and is undefined for person2.

Now, let’s set the age property on the prototype of Person:

// Step 6: Set a property on the prototype
Person.prototype.age = 25;

// Step 7: Access the age property again
console.log(person1.age); // Output: 30
console.log(person2.age); // Output: 25

Now, both person1 and person2 have access to the age property even though it was added to the prototype after person1 was created.

This demonstrates that properties set on the prototype are shared among all instances of the object type.

Question 2

How do you check if an object inherits a specific property from its prototype?

Answer:

You can use the hasOwnProperty() method to check if an object has a specific property.

If the property is inherited from the prototype chain, this method returns false. For example:

if (object.hasOwnProperty('propertyName')) {
  // Property is directly defined on the object
} else {
  // Property is inherited
}
Code Example 

// Define a constructor function
function Person(name) {
  this.name = name;
}

// Add a method to the prototype
Person.prototype.greet = function() {
  return "Hello, my name is " + this.name;
};

// Create an instance of Person
var person1 = new Person("Alice");

// Check if 'name' property is inherited
console.log(person1.hasOwnProperty('name')); 
// Output: true (directly defined on 'person1')
console.log(person1.hasOwnProperty('greet')); 
// Output: false (inherited from prototype)

In this example:

  • We use hasOwnProperty('name') to check if the name property is directly defined on the person1 object. Since name is defined directly on person1, it returns true.
  • Similarly, we use hasOwnProperty('greet') to check if the greet method is directly defined on the person1 object. Since greet is inherited from the prototype, it returns false.

By using hasOwnProperty(), you can distinguish between properties that are directly defined on an object and those that are inherited from its prototype chain.

Question 3

How do you create a constructor function with prototypes in JavaScript?

Answer:

You can define a constructor function and then add properties and methods to its prototype.

For example:

function MyClass() {
  // Constructor function
}
MyClass.prototype.myMethod = function() {
  // Method implementation
};

Question 4

Create a Person constructor function with name and age properties. Add a method greet() to its prototype that returns a greeting with the person's name and age.

Answer:

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

Person.prototype.greet = function() {
  return "Hello, my name is " + this.name + " and I'm " + this.age + " years old.";
};

var person1 = new Person("Soni", 30);
console.log(person1.greet()); 
// Output: Hello, my name is Soni and I'm 30 years old.

Question 5

Implement a simple inheritance pattern using prototypes. Create a Vehicle constructor with a type property. Create a Car constructor that inherits from Vehicle and adds a color property.

Answer:

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

function Car(type, color) {
  Vehicle.call(this, type); // Call the parent constructor
  this.color = color;
}

Car.prototype = Object.create(Vehicle.prototype); // Inherit from Vehicle

var car1 = new Car("SUV", "blue");
console.log(car1.type); // Output: SUV
console.log(car1.color); // Output: blue

Question 6

What happens if you modify a property on an object’s prototype?

Answer:

If you modify a property on an object’s prototype, the change affects all objects that inherit from that prototype.

However, if the property is shadowed by a property with the same name on the object itself, the object’s property takes precedence.

Example

// Define a constructor function
function Person(name) {
  this.name = name;
}

// Add a method to the prototype
Person.prototype.greet = function() {
  return "Hello, my name is " + this.name;
};

// Create an instance of Person
var person1 = new Person("Soni");

// Modify the prototype property
Person.prototype.greet = function() {
  return "Hey there, I'm " + this.name;
};

// Access the method from the instance
console.log(person1.greet()); // Output: Hey there, I'm Soni

In this example, the greet() method is originally added to the Person prototype.

However, it is later modified to have a different implementation. Despite creating an instance of Person before the modification, the change in the prototype's method affects all instances of Person, including person1.

Therefore, when person1.greet() is called after the modification, it reflects the updated behavior defined on the prototype.

Question 7

Explain the difference between prototype and property in JavaScript.

Answer:

A prototype is an object from which other objects inherit properties.

Every object in JavaScript has an internal property called [[Prototype]] (accessible via Object.getPrototypeOf() or __proto__ in modern browsers) that points to its prototype.

var vehiclePrototype = {
  wheels: 4,
  move: function() {
    return 'Moving forward...';
  }
};

var car = Object.create(vehiclePrototype);
console.log(car.wheels); // Output: 4
console.log(car.move()); // Output: Moving forward...

A property is a key-value pair associated with an object, which can be either directly set on the object or inherited from its prototype.

var car1 = new Car("SUV", "blue");
console.log(car1.type); // Output: SUV
console.log(car1.color); // Output: blue

Difference:

  • The key difference between a prototype and a property is that a prototype is an object itself, while a property is a key-value pair associated with an object.
  • Prototypes establish a chain of inheritance, allowing objects to inherit properties and methods from their prototypes, while properties define the state or characteristics of an object.
  • Prototypes are used for sharing behavior among objects, while properties represent the data stored within an object.

Below Questions for reader’s to try and provide code sample to contribute :)

Happy learning

1 Create a Counter object with a count property initialized to 0. Add methods increment() and decrement() to its prototype that increase and decrease the count respectively.

2 Create a generic object Shape with a type property. Define Circle and Rectangle constructors that inherit from Shape and have additional properties like radius and length & width respectively.

In interviews, understanding how prototypes work is crucial for demonstrating proficiency in JavaScript, as it is a fundamental concept in the language’s object-oriented programming model.

Kind is cool !!! Share knowledge to gain knowledge !!!! Be kind and treat people with respect !!!

If you find my videos helpful, then please subscribe, Claps and follow to support

Cheers, Kirti Kaushal

If you find my blogs helpful, then please subscribe ,Claps and follow to support me in GitHub too.

Other’s article

Javscript
Javascript Interview
100 Days Of Learning
100 Days Writing
Programming
Recommended from ReadMedium