Leonardo
Leonardo

Reputation: 303

Object checking issue in JavaScript

In this code I'm checking if every key in the obj is squared value of arr. also checking if values of obj is equal to corresponding value quantity of arr. so I'm iterating arr and by using in operator checking if key ** 2 exists in obj, if not doing console.log("false") if yes making subtraction of obj's property and doing console.log("true")

let obj = {
  1: 1,
  4: 1,
  9: 1,
  25: 2,
};

let arr = [1, 2, 3, 2, 5];

for (let key of arr) {
  if (!(key ** 2 in obj)) {
    console.log("false");
  } else {
    obj[key ** 2] -= 1;
    console.log(obj);
    console.log("true");
  }
}
enter image description here

Here I changed in operator with (obj[key ** 2]), so my question is not how to solve task properly, my question is that why in case of in operator and "(obj[key ** 2])" they act the way they do? in the in operator case subtraction of -1 continues, but in the second case, the moment when obj's key is 4 and property 0 it stops subtraction, which means that !(obj[2 ** 2]) is true therefore logs "false".

so again why in the both case they act the way they do? is there some rule or something like that? I think first case seems more logically, Thanks in advance

let obj = {
  1: 1,
  4: 1,
  9: 1,
  25: 2,
};

let arr = [1, 2, 3, 2, 5];

for (let key of arr) {
  if (!(obj[key ** 2])) {
    console.log("false");
  } else {
    obj[key ** 2] -= 1;
    console.log(obj);
    console.log("true");
  }
}
enter image description here

Upvotes: 0

Views: 62

Answers (1)

miraj
miraj

Reputation: 586

The in operator returns true if the specified property is in the specified object or its prototype chain. whereas, obj[key] returns the value of that key. so when obj[4] becomes 0 first block of if conditional executes. As if(!0) == true

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in

in your 1st code, you are checking the keys with !(keys ** 2 in obj). whenever the key is matched it returns true. As if(!true) == false the 1st block of if statement is skipped.

Upvotes: 2

Related Questions