Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Using hasOwnProperty() method in "for...in" loop JS

    • 0
    • 0
    • 0
    • 0
    • 1
    • 0
    • 0
    • 0
    • 382
    Comment on it

    We all know that for...in loop is used to iterate over enumerable properties of object as well as properties of its prototypes, but what if we want to iterate over properties attached to the object itself, and not its prototypes.

    this is where hasOwnProperty() method plays its role...eg shown below -:

    var square = {a:1, b:2, c:3};
    
    function ColoredSquare() {
      this.color = "red";
    }
    
    ColoredSquare.prototype = square;
    
    var obj = new ColoredSquare();
    console.log(obj)                // you can see object contains all the properties...
    for (var prop in obj) {
      if( obj.hasOwnProperty( prop ) ) {     // condition to filter its own properites...
        console.log("obj." + prop + " = " + obj[prop]);
      } 
    }
    // Output:
    //  Object { color="red",  a=1,  b=2,  c=3}
    // "obj.color = red"
    

    In above example you can see that 'hasOwnProperty()' method will check whether it is objects own property or not and if it is, then methods will return 'true' otherwise 'false'...

 1 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: