0

I need some condition to catch and throw error when a non-function data type is passed as the second argument.

Including undefined being passed?

function test(fn) {
  console.log(fn)
  // should throw an error if a non-function data type is 
  //passed as the second argument (includes undefined being passed)
  if (fn && typeof fn !== 'function') throw Error();
  return fn;
}


function demo() {}

test(); //undefined OK!

test(undefined); // SHOULD THROW ERROR ALSO

// throws error since argument is defined and not a function
test('sdfasfs'); 
Sahin Erbay
  • 994
  • 2
  • 12
  • 24

3 Answers3

1

It will not throw an error because of fn condition in if which will be evaluated to false for undefined and hence, if is not evaluated to true and error is not thrown.

If you are looking for throwing an error if undefined is passed then, you can update your code to following

function test(fn) {
  console.log(fn)
  // should throw an error if a non-function data type is 
  //passed as the second argument (includes undefined being passed)
  if ((fn || fn === undefined) && typeof fn !== 'function') throw Error();
  return fn;
}

function demo() {}

test(); //undefined OK!

test(undefined); // WILL THROW ERROR

// throws error since argument is defined and not a function
test('sdfasfs'); 
Nikhil Aggarwal
  • 28,197
  • 4
  • 43
  • 59
1

The only way to distinguish between implicitly and explicitly passing undefined is to look at how many arguments have been passed:

function test(fn) {
  console.log(fn)
  // should throw an error if a non-function data type is 
  //passed as the second argument (includes undefined being passed)
  if (arguments.length > 0 && typeof fn !== 'function') throw Error();
  return fn;
}


function demo() {}

test(); //undefined OK!

test(undefined); // SHOULD THROW ERROR ALSO

// throws error since argument is defined and not a function
test('sdfasfs'); 
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
0

Because of the fact that undefined is falsy in JS, your first condition prevent you from throwing.

Just remove the first condition.

function test(fn) {
  console.log(fn)
  // should throw an error if a non-function data type is 
  //passed as the second argument (includes undefined being passed)
  if (typeof fn !== 'function') throw Error();
  return fn;
}


function demo() {}

test(); //undefined OK!

test(undefined); // SHOULD THROW ERROR ALSO

// throws error since argument is defined and not a function
test('sdfasfs');
felixmosh
  • 32,615
  • 9
  • 69
  • 88
  • Then `test()` will throw though. Maybe that's what the OP wants, but it's unclear to me because of the `//undefined OK!` comment. – Felix Kling May 11 '18 at 05:16