- Published on
What is the difference between using {} and not using {} in import statements?
- Authors
- Name
- hwahyeon
In JavaScript, the use of {}
in import
statements indicates a difference in how modules are imported.
Analogy for Understanding
- Default export is like the main title of a book—there’s only one, and you can refer to it by any name.
- Named exports are like chapter titles in a book—there can be many, and you need to use the exact name.
1. Default Export
- Used when a module exports a single main value.
- The export is written as
export default
. - When importing, you don’t use
{}
, and you can name it whatever you like.
Example:
// module.js
export default function sayHello() {
console.log('Hello!')
}
// main.js
import greet from './module.js'
greet() // Outputs: 'Hello!'
A module can have only one default export, which can be imported with any name you choose.
2. Named Export
- Used when a module exports multiple values with specific names.
- Exported with the
export
keyword. - When importing, you must use
{}
and import by the exact name.
Example:
// module.js
export function add(a, b) {
return a + b
}
export const c = 3
// main.js
import { add, c } from './module.js'
console.log(add(2, 3)) // Outputs: 5
console.log(c) // Outputs: 3
You can import multiple named exports at once by using {}
.
Using Both Default and Named Exports Together
A module can export both a default export and named exports at the same time.
Example:
// module.js
export default function defaultFunction() {
console.log('Default function')
}
export function namedFunction() {
console.log('Named function')
}
// main.js
import defaultFunction, { namedFunction } from './module.js'
defaultFunction() // Outputs: 'Default function'
namedFunction() // Outputs: 'Named function'
Import the default export without {}
and the named exports with {}
.