Skip to content

Instantly share code, notes, and snippets.

@vrunoa
Last active August 29, 2015 14:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vrunoa/47b9d84fb53a7a03e09a to your computer and use it in GitHub Desktop.
Save vrunoa/47b9d84fb53a7a03e09a to your computer and use it in GitHub Desktop.
ES6 default export value ?

I've been using babel on a few projects, and on my last project I got myself with this question;

I have a scan function where I want to set 2 default values

export default function scan({
  tmpFolder = "./tmp", 
  verbose = false
}){
// function body
}

When importing the module into my bin project I have to set an empty {} as param

var scan = require('scan');
scan({})

Otherwise, if I dont set it;

var scan = require('scan');
scan()

i'm getting an error;

var _ref$tmpFolder = _ref.tmpFolder;
                           ^
TypeError: Cannot read property 'tmpFolder' of undefined

Why am I getting an error if I don't set an empty {}? Shouldnt be {tmpFolder = "./tmp",verbose = false} the default value ? Is this a Babel issue or is it wrong to don't set an empty {} in this case ?

@loganfsmyth
Copy link

Your logic splits up into

export default function scan(param){
  let {
    tmpFolder = "./tmp", 
    verbose = false
  } = param;

// function body
}

which should make it clear that when you call the function with no arguments, you are assigning undefined to an object pattern, which makes it throw. To work, you need to give param a default value, e.g.

export default function scan(param = {}){

or combine all together:

export default function scan({
  tmpFolder = "./tmp", 
  verbose = false
} = {}){
// function body
}

@vrunoa
Copy link
Author

vrunoa commented Jun 16, 2015

This is what I was looking for:

export default function scan({
  tmpFolder = "./tmp", 
  verbose = false
} = {}){
// function body
}

And then use scan()

Thanks @loganfsmyth

@ericelliott
Copy link

:)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment