📜 ⬆️ ⬇️

Checking the existence of properties and methods of an object in Javascript

I found in the Javascript library code the following structure:

if ('is_public' in profile) {

Very interested in how it works. Before that, I used the 'in' operator only for iteration, and here is an interesting check. Having rummaged, I found for myself that the 'in' operator can also be used to check for the existence of an object method, object properties, and the index of an element in an array. Below are a few examples:

var Test = function() { return this; };

Test.prototype.myFunc = function() {};

var testInstance = new Test();

console.info('myFunc' in testInstance); // will return 'true'
console.info('myFunc2' in testInstance); // will return 'false'

var myObject = {test: 1};

console.info('test' in myObject); // will return 'true'
console.info('test1' in myObject); // will return 'false'

var myArray = [4,3,1];

console.info(1 in myArray); // will return 'true'
console.info(3 in myArray); // will return 'false'

The better such a check than just check like this?

var myArray = [4,3,1];

if (myArray[3] != undefined) {

The answer is simple, because your array may contain an element under this index, but the value of this element will be 'undefined', in this case you can not be sure of its existence. The 'in' operator checks for the existence of an element / property / method. Perhaps you will not use it often or will not use it at all, but I think that it will be very good to know.


Source: https://habr.com/ru/post/104186/

All Articles