2

I have javascript class like this

class Student {
  constructor(name, age) {}
}

How to rise or return an error message when one of paramaters (lets say 'name') not being passed. something like :

if (!name) {
  return "whoops, you forget a name"
}
  • do you mean something like `console.error('Student has no name')`? I mean what do you want to happen? – SuperDJ Aug 19 '18 at 11:41
  • Possible duplicate of [Test if something is not undefined in JavaScript](https://stackoverflow.com/questions/7041123/test-if-something-is-not-undefined-in-javascript) – lleon Aug 19 '18 at 11:42
  • 2
    `throw new Error("whoops, you forget a name")` – Keith Aug 19 '18 at 11:42
  • Yes. i know how to use throw Error or console.error. But where i should put that line on my code? is it inside contructor or somewhere else? – Jim Johnson Aug 19 '18 at 12:00

2 Answers2

4

The expression throwIfMissing() specifying the default value is evaluated, if the passed value is missing.

    function throwIfMissing() {
       throw new Error('Missing parameter');
    }

    class Student{
        constructor(mustBeProvided = throwIfMissing()) {
             return mustBeProvided;
         }
    }
    var student = new Student(100); //works
    console.log(student);
    var err = new Student(); // throws Uncaught Error: Missing parameter
Fullstack Guy
  • 16,368
  • 3
  • 29
  • 44
1

Look at the arguments object and see how many parameters it has. It is not correct just to test to see if its value is undefined as it may have been set to undefined.

QuentinUK
  • 2,997
  • 21
  • 20