2018-09-30 23:01:58 +01:00
---
id: 587d7dae367417b2b2512b7a
title: Verify an Object's Constructor with instanceof
challengeType: 1
2019-08-05 09:17:33 -07:00
forumTopicId: 301337
2021-01-13 03:31:00 +01:00
dashedName: verify-an-objects-constructor-with-instanceof
2018-09-30 23:01:58 +01:00
---
2020-11-27 19:02:05 +01:00
# --description--
Anytime a constructor function creates a new object, that object is said to be an < dfn > instance</ dfn > of its constructor. JavaScript gives a convenient way to verify this with the `instanceof` operator. `instanceof` allows you to compare an object to a constructor, returning `true` or `false` based on whether or not that object was created with the constructor. Here's an example:
2019-05-17 06:20:30 -07:00
```js
let Bird = function(name, color) {
this.name = name;
this.color = color;
this.numLegs = 2;
}
let crow = new Bird("Alexis", "black");
crow instanceof Bird; // => true
```
2020-11-27 19:02:05 +01:00
If an object is created without using a constructor, `instanceof` will verify that it is not an instance of that constructor:
2019-05-17 06:20:30 -07:00
```js
let canary = {
name: "Mildred",
color: "Yellow",
numLegs: 2
};
canary instanceof Bird; // => false
```
2020-11-27 19:02:05 +01:00
# --instructions--
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
Create a new instance of the `House` constructor, calling it `myHouse` and passing a number of bedrooms. Then, use `instanceof` to verify that it is an instance of `House` .
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
# --hints--
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
`myHouse` should have a `numBedrooms` attribute set to a number.
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
```js
assert(typeof myHouse.numBedrooms === 'number');
2018-09-30 23:01:58 +01:00
```
2020-11-27 19:02:05 +01:00
You should verify that `myHouse` is an instance of `House` using the `instanceof` operator.
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
```js
assert(/myHouse\s*instanceof\s*House/.test(code));
```
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
# --seed--
## --seed-contents--
2018-09-30 23:01:58 +01:00
```js
function House(numBedrooms) {
this.numBedrooms = numBedrooms;
}
2020-03-08 07:46:28 -07:00
// Only change code below this line
2018-09-30 23:01:58 +01:00
```
2020-11-27 19:02:05 +01:00
# --solutions--
2018-09-30 23:01:58 +01:00
```js
function House(numBedrooms) {
this.numBedrooms = numBedrooms;
}
const myHouse = new House(4);
console.log(myHouse instanceof House);
```