Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript function should throw an error if called without arguments or an argument is undefined

Help! I'm being interviewed on Tuesday, including a test on testdome.com... I looked at some of their "easy" javascript practise questions, and I'm stumped on this one:

Implement the ensure function so that it throws an error if called without arguments or an argument is undefined. Otherwise it should return the given value.

function ensure(value) {

}

So far, I've got:

function ensure(value) {
  if(value){
    return true;
  }
}

But how do I check if if the function is called "without arguments or an argument is undefined"?

I've tried a few things, like: else if (typeof value === 'undefined'), but that doesn't seem to work...

like image 527
Andy Avatar asked Jul 02 '17 19:07

Andy


2 Answers

You can check if value === undefined, and if so throw an error. Otherwise return the input value.

function ensure(value) {
  if(value === undefined) {
    throw new Error('no arguments');
  }

  return value;
}

console.log(ensure('text'));
console.log(ensure([0,1,2,3]));
console.log(ensure());
like image 81
Brett DeWoody Avatar answered Nov 19 '22 08:11

Brett DeWoody


 function noValueException(value) {
       this.value = value;
       this.name = 'noValueException';
    }

    function ensure(value) {
      if(value === undefined){
          throw new noValueException('No argument passed');       
      }else{ return value;}
    }

This will throw an exception to console if no argument is passed to function

like image 27
praveen Avatar answered Nov 19 '22 09:11

praveen