30 Days of JAVASCRIPT #13/30

4. Prototyes and Modules(export/import)

Prototypes and modules are two important concepts in JavaScript that help developers write more efficient and organized code. In this blog post, we will discuss what prototypes and modules are and how to use them in JavaScript.

Prototypes

Prototypes are a fundamental concept in JavaScript that allow objects to inherit properties and methods from other objects. Every object in JavaScript has a prototype, which is an object that it inherits properties and methods from. When a property or method is accessed on an object, JavaScript first looks for it on the object itself. If it is not found, it looks for it on the object's prototype, and so on up the prototype chain until it reaches the top-level Object.prototype.Here is an example code that demonstrates the use of prototypes:

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

Person.prototype.sayHello = function() {
  console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
};

const john = new Person("John", 30);
john.sayHello(); // Output: Hello, my name is John and I am 30 years old.

In the above code, we define a Person constructor function and add a sayHello() method to its prototype. We then create an object john using the Person constructor and call its sayHello() method.

Modules

Modules are a way to organize code into separate files and reuse functionality across different parts of an application. In JavaScript, modules are implemented using the import and export keywords.Here is an example code that demonstrates the use of modules:

// In file1.js
export function add(a, b) {
  return a + b;
}

// In file2.js
import { add } from "./file1.js";

console.log(add(2, 3)); // Output: 5

In the above code, we define a add() function in file1.js and export it using the export keyword. We then import this function in file2.js using the import keyword and call it to print the result to the console.

Conclusion

Prototypes and modules are two important concepts in JavaScript that help developers write more efficient and organized code. Prototypes allow objects to inherit properties and methods from other objects, while modules allow code to be organized into separate files and reused across different parts of an application. By understanding and using these concepts, developers can write more maintainable and scalable JavaScript code.