-1

I have an add.js I do this it's valid

const add = (a, b) => {
    return a + b;
}

export default add;

but why can't I do this

export default add(a, b) => (a + b) ? I will get add is undefined.

another file i have

import add from './add';
Alex Yong
  • 7,425
  • 8
  • 24
  • 41

2 Answers2

4

If you just want to export the function directly as the default, you literally just do that (no add):

export default (a, b) => a + b;

The import will determine the identifier used to reference it.

If you want the function to have a name (e.g., a name property populated with something other than the default value), you'd either make it a function function:

export default function add(a, b) { return a + b; };

or do it in two parts as you did originally:

const add = (a, b) => a + b;
export default add;

(Note that the () around a + b in the arrow function are unnecessary, although of course you may choose to have them as a matter of style.)

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
-1

Because this is not a proper way to declare variable/constant in JS. Only var/constant defined properly gets space (memory).

Therefore, you need to do like this

const add;

or

let add;

or

var add;

May be my explanation was not proper but I meant when you are exporting even in that case you need to use const, var or let for proper declaration if you have not declared a variable already.

Nitesh
  • 1,490
  • 1
  • 12
  • 20
  • May I know, why it has been downvoted? – Nitesh Feb 24 '17 at 07:48
  • *"when you are exporting even in that case you need to use const, var or let for proper declaration"* No, you don't. I don't know if that last paragraph was there when it was downvoted (the phrasing suggests not), but if so, that's probably why. (If not, it was probably that it wasn't clear you were addressing the `export default` aspect at all.) – T.J. Crowder Feb 24 '17 at 08:11
  • Thank you for explanation but what I actually meant was if you have declared a variable already then it is fine but if you have not declared you need to use const/let/var while using export. Initially, I didn't mention that last paragraph because I was mentioning just why user can't directly use any name with export without declaration. Now, I edited my answer for better explanation. By the way, thanks I will keep in mind to have good explanation from next time. – Nitesh Feb 24 '17 at 08:36
  • *"but if you have not declared you need to use const/let/var while using export"* As I said above: No, you don't. See my answer. `export default (a, b) => a + b;` is perfectly valid. Not a `let` or `const` or `var` in sight. :-) – T.J. Crowder Feb 24 '17 at 09:03