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:
- p1 refers to the default export from the module ./myFile.js.
- A module can have only one default export.
- The default export can be any value: an object, a function, a class, a primitive value, etc.
- When you import a default export, you can name it whatever you like in the importing file.
{p2}:
- p2 refers to a named export from the module ./myFile.js.
- A module can have multiple named exports.
- Named exports must be imported using their exact names inside curly braces {}.
- 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)