-3

Ok so I have seen the in keyword in many different codes but i have never understood what they do. Here is an example

let duck = new Bird() // Bird is a constructor i made. Not important
function in keyword() {
    let ownProps = [];

for (let property in duck) {
  if(duck.hasOwnProperty(property)) {
    ownProps.push(property);
  }
}
}

Sooo, what does it do? Please explain it to me

Aaseer
  • 117
  • 10

1 Answers1

0

The in operator tests if the string on the left side of the operator is a property name in the object on the right side.

let obj = { a: 1 };
console.log("a" in obj); // true
console.log("b" in obj); // false

The in keyword also plays a role in the for ... in loop, which iterates through the properties (the enumerable properties) of an object:

let obj = { a: 1, b: 2 };
for (let x in obj) {
  console.log(x);
}

That will log "a" and "b", because those are the enumerable properties of the object.

Pointy
  • 405,095
  • 59
  • 585
  • 614