-1

I'm trying to let a user optionally pass in an options parameter to a function to override a default variable like this:

 let methodName = (options && options.methodName) || 'getSpaces';

However, when I put this line into my node CLI I get an error: ReferenceError: options is not defined.

How come I can't do this sort of thing?

MarksCode
  • 8,074
  • 15
  • 64
  • 133

3 Answers3

2

If you don't know whether options will be even defined or not, you can do:

let methodName = (typeof(options) !== 'undefined' && options.methodName) || 'getSpaces';
JCOC611
  • 19,111
  • 14
  • 69
  • 90
1

Do it like this

let options;
let methodName = (options && options.methodName) || 'getSpaces';

You are trying to access variable that does not exist, that is the reason it throws this error. You will have the same error if you paste the same code even in the browser console, because the same reasons.

0

The function declaration seems wrong to me. It can be either one of the below:

    let methodName = (options) => ((options && options.methodName)  || 'getSpaces');
    let otherMethod = (methodName = "getSpaces") => (methodName)
    console.log(methodName())  //getSpaces
    console.log(methodName({methodName:"testMethod"}))  //testMethod
    console.log(otherMethod())  //getSpaces
    console.log(otherMethod("anotherTestMethod"))  //anotherTestMethod
CRayen
  • 569
  • 2
  • 11