DEV Community

Kiran
Kiran

Posted on

Imports in JS

While interviewing yesterday, I was asked the following question: "import p1, {p2} from './myFile.js;'" What is the difference between p1 and {p2}?

After using this for several years, I got stuck and failed to explain it properly.

Here is the simplest explanation for this.

p1:

  1. p1 refers to the default export from the module ./myFile.js.
  2. A module can have only one default export.
  3. The default export can be any value: an object, a function, a class, a primitive value, etc.
  4. When you import a default export, you can name it whatever you like in the importing file.

{p2}:

  1. p2 refers to a named export from the module ./myFile.js.
  2. A module can have multiple named exports.
  3. Named exports must be imported using their exact names inside curly braces {}.
  4. We can rename a named export while importing it by using the syntax import { originalName as newName } from 'module-path';.

Example:

// ./myFile.js

// Default export
const defaultExport = "I am the default export";
export default defaultExport;

// Named export
const namedExport = "I am a named export";
export const p2 = namedExport;

//imported file

import p1, { p2 } from './myFile.js';

console.log(p1); // Output: "I am the default export"
console.log(p2); // Output: "I am a named export"

Top comments (0)