Checking for the existence of object properties and methods in Javascript

    I found this construction in the Javascript code of the library: I was very interested in how it works. Prior to that, I used the 'in' operator only for iteration, but here such a check is interesting. Having rummaged around, I found for myself that the 'in' operator can also be used to check the existence of an object method, object property, and element index in an array. Below are a few examples: What is better than such a check than just checking so?

    if ('is_public' in profile) {
    ...
    }




    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'




    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 which case you cannot be sure of its existence. The 'in' operator verifies precisely 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.

    Also popular now: