When do we put ( ) in export function in JavaScript? like what is the difference between these code:
function Hello() {
return "Hello World"
}
export Hello
and
function Hello() {
return "Hello World"
}
export Hello()
CodePudding user response:
When you use this
function Hello() {
return "Hello World"
}
export Hello
you are exporting your function.. therefore when you import it
import {Hello} from "hello.js"
console.log(typeof Hello) // "function"
console.log(Hello()) // "Hello World"
if you use this:
function Hello() {
return "Hello World"
}
export Hello()
you are calling Hello
function, and exporting its returning value, but you need to assign it to variable, or export it as default
function Hello() {
return "Hello World"
}
export default Hello()
or
function HelloFc() {
return "Hello World"
}
export const Hello = HelloFc()
and then import will look like this
import {Hello} from "hello.js"
console.log(typeof Hello) // "string"
console.log(Hello()) // Uncaught TypeError: "Hello" is not a function
CodePudding user response:
Basically both are not working!
If you want to export function Hello, let's use export { Hello }
.
If you want to export return value of Hello function, let's use export default Hello()
.