4
An unexpected behavior (at least for me) occurred with the following excerpt of code that I will demonstrate below:
const str = new String('olá SOpt');
console.log('Usando "in"', 'length' in str); // true
console.log('Usando "hasOwnProperty"', str.hasOwnProperty('length')); // true
Note that so far, nothing new, worked as expected, but the code below made me have doubts:
const str = 'olá SOpt';
console.log('Usando "hasOwnProperty"', str.hasOwnProperty('length'));
console.log('Usando "in"', 'length' in str); // vai lançar um erro
If you run the code above, the second console.log
will have a mistake saying something like:
Uncaught Typeerror: Cannot use 'in' Operator to search for 'length' in olá Sopt
That’s when the doubts arose...I hoped it would work normally the use of the in
because a string has a property length
const str = 'olá SOpt';
console.log('Usando "hasOwnProperty"', str.hasOwnProperty('length'));
console.log('lenght: ', str.length); // 8
Only using 'length' in str
returned an error. Obviously, my line of reasoning in finding that in
and hasOwnProperty
were the same thing, only one way "dry" of writing, had failed:
const str = new String('olá SOpt');
console.log('Usando "in"', 'length' in str);
console.log('Usando "hasOwnProperty"', str.hasOwnProperty('length'));
const str2 = 'olá SOpt';
console.log('Usando "hasOwnProperty"', str2.hasOwnProperty('length'));
try {
console.log('Usando "in"', 'length' in str2); // ocorre um erro
} catch (error) {
console.log(
`Erro ao usar o "in" em: console.log('Usando "in"', 'length' in str2);`,
);
}
Questions
- What is the difference between the operator
in
and the methodhasOwnProperty
? - When using one or the other?
- Why the
in
in string declared usingnew String('foo')
works, but does not work with'foo'
?
Just out of curiosity, I tried to use in structure Map
, but apparently, only .has()
works for the same:
let map = new Map();
map.set('name', 'Cardeal');
console.log('name' in map); // false
console.log(map.hasOwnProperty('name')); // false
console.log(map.has('name')); // true