0

Is there a way to make sure the input for a property is a certain Type? In this example I want to check whether the new Lion has a mane. Is there a way to make sure that the 'mane' value is a Boolean, when creating a new Lion Object?

function Lion(height, weight, fur, purr, mane) {
  Cat.call(this, name, height, weight, fur, purr);
  this.name = 'Lion';
  this.mane = mane;
};

var lion1 = new Lion('100cm', '250kg', 'beige', 'ROAAAAAAAAR!', true);
Vincent
  • 137
  • 2
  • 15

2 Answers2

0

You could force whatever mane is to be a boolean by using Boolean(mane) it will output true/false based on Javascript truthy/falsey values and always guarantree mane is a boolean.

this.mane = Boolean(mane);
Barmar
  • 741,623
  • 53
  • 500
  • 612
AHB
  • 548
  • 2
  • 7
  • I think `!!mane` is the more idiomatic way to do this. It doesn't call a function or box it into an object. – Barmar Sep 14 '17 at 21:16
  • Sure the output is the same but for someone not familiar with JS putting !! in front of a variable name is probably not very readable. – AHB Sep 14 '17 at 21:20
  • You could link to this question: https://stackoverflow.com/questions/784929/what-is-the-not-not-operator-in-javascript/784946#784946 – Barmar Sep 14 '17 at 21:23
0

You can use the typeof operator to perform that check when creating the new object:

function Lion(height, weight, fur, purr, mane) {
  Cat.call(this, name, height, weight, fur, purr);
  this.name = 'Lion';
  if (typeof mane === "boolean") {
    this.mane = mane;
  } else {
    throw "type error" // or do whatever
  }
};
nvioli
  • 4,137
  • 3
  • 22
  • 38