DEV Community

Cover image for What is Export and Import in JavaScript?
Rahul
Rahul

Posted on • Updated on

What is Export and Import in JavaScript?

My new post for beginners and learners. So here We'll learn about Import and Export in a very very easy way. Let's go

Import and Export

  • In JavaScript ES6, we can import and export functionalities from modules.
  • These can be functions, classes, components, constants, essentially anything assign to a JavaScript variable.
  • Modules can be single files or a whole folder with one index file as an entry point.

Why to use Import and Export

  • The import and export statements in JavaScript help you to share code across multiple files to keep it reusable and maintainable.
  • Encapsulation : Since not every function needs to be exported from a file. Some of these functionalities should only be used in files where they have been defined. File exports are a public API to a file, where only the exported functionalities are available to be reused elsewhere. This follows the best practice of encapsulation.

Export before declaration

export const name = Rahul;
export function sayHi(user) {
    alert(`Hello, ${user}!`);
} // no; at the end
Enter fullscreen mode Exit fullscreen mode

And import them in another file with a relative path to the first file.

import { name } from './firstfile.js';
console.log(name); // Rahul
sayHi(name); // Hello, Rahul!

import * as person from './firstfile.js'; 
console.log(person.name); // Rahul
Enter fullscreen mode Exit fullscreen mode

Imports can have aliases, which are necessary when we import functionalities from multiple files that have the same-named export.

import { name as firstName, sayHi } from './firstfile.js'; 
console.log(firstName); // Rahul
Enter fullscreen mode Exit fullscreen mode

There is also default statement, which can be used for a few cases:

  • To export and import a single functionality
  • To highlight the main funuctionality of the exported API o a module To have a fallback import functionality
const person = {
    firstName: 'Rahul',
    lastName: 'Singh',
};
export default person; 
Enter fullscreen mode Exit fullscreen mode

We can leave out the curly braces to import the default export.

import developer from './firstfile.js';
console.log(developer); 
// { firstName: 'Rahul', lastName: 'Singh' }
Enter fullscreen mode Exit fullscreen mode

That was it explaining the import and export in JavaScript. Hope you have found it useful.


Need Help

Need help in raising funds to buy a Mechanical Keyboard. This pandemic has affected my family badly so can't ask my DAD for it. Please Help Me.


1.png

😎Happy Coding | Thanks For Reading⚡

Top comments (1)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.