When do I need to use hasOwnProperty()











up vote
11
down vote

favorite
2












I read that we should always use hasOwnProperty when looping an object, because the object can be modified by something else to include some keys we don't want



But is this always required? Are there situations where it's not needed? Is this required for local variables too?



function my(){
var obj = { ... };
for(var key in obj){

if(obj.hasOwnProperty(key)){
safe
}

}
}


I just don't like adding an extra if inside the loop if I don't have to.



http://phrogz.net/death-to-hasownproperty



This guy says I shouldn't use it all anymore.










share|improve this question




























    up vote
    11
    down vote

    favorite
    2












    I read that we should always use hasOwnProperty when looping an object, because the object can be modified by something else to include some keys we don't want



    But is this always required? Are there situations where it's not needed? Is this required for local variables too?



    function my(){
    var obj = { ... };
    for(var key in obj){

    if(obj.hasOwnProperty(key)){
    safe
    }

    }
    }


    I just don't like adding an extra if inside the loop if I don't have to.



    http://phrogz.net/death-to-hasownproperty



    This guy says I shouldn't use it all anymore.










    share|improve this question


























      up vote
      11
      down vote

      favorite
      2









      up vote
      11
      down vote

      favorite
      2






      2





      I read that we should always use hasOwnProperty when looping an object, because the object can be modified by something else to include some keys we don't want



      But is this always required? Are there situations where it's not needed? Is this required for local variables too?



      function my(){
      var obj = { ... };
      for(var key in obj){

      if(obj.hasOwnProperty(key)){
      safe
      }

      }
      }


      I just don't like adding an extra if inside the loop if I don't have to.



      http://phrogz.net/death-to-hasownproperty



      This guy says I shouldn't use it all anymore.










      share|improve this question















      I read that we should always use hasOwnProperty when looping an object, because the object can be modified by something else to include some keys we don't want



      But is this always required? Are there situations where it's not needed? Is this required for local variables too?



      function my(){
      var obj = { ... };
      for(var key in obj){

      if(obj.hasOwnProperty(key)){
      safe
      }

      }
      }


      I just don't like adding an extra if inside the loop if I don't have to.



      http://phrogz.net/death-to-hasownproperty



      This guy says I shouldn't use it all anymore.







      javascript loops object






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Sep 6 '15 at 13:11

























      asked Sep 6 '15 at 11:07









      Anna K.

      53221031




      53221031
























          3 Answers
          3






          active

          oldest

          votes

















          up vote
          22
          down vote



          accepted










          Object.hasOwnProperty determines if the whole property is defined in the object itself or in the prototype chain.



          In other words: do the so-called check if you want properties (either with data or functions) coming from no other place than the object itself.



          For example:



          function A() {
          this.x = "I'm an own property";
          }

          A.prototype.y = "I'm not an own property";

          var instance = new A();
          var xIsOwnProperty = instance.hasOwnProperty("x"); // true
          var yIsOwnProperty = instance.hasOwnProperty("y"); // false


          Do you want to avoid the whole check if you want own properties only?



          Since ECMA-Script 5.x, Object has a new function Object.keys which returns an array of string where its items are the own properties from a given object:



          var instance = new A();
          // This won't contain "y" since it's in the prototype so
          // it's not an "own object property"
          var ownPropertyNames = Object.keys(instance);


          Also, since ECMA-Script 5.x, Array.prototype has Array.prototype.forEach which lets perform a for-each loop fluently:



          Object.keys(instance).forEach(function(ownPropertyName) {
          // This function will be called for each found "own property", and
          // you don't need to do the instance.hasOwnProperty check anymore
          });





          share|improve this answer























          • Great example !
            – elad.chen
            Sep 6 '15 at 11:15










          • @elad.chen Thanks ;P Simple but still efficient!
            – Matías Fidemraizer
            Sep 6 '15 at 11:15










          • I would consider adding the usage of Object.keys(obj).forEach(..); As this will prevent prototype lookups..
            – elad.chen
            Sep 6 '15 at 11:17












          • @elad.chen Right, I can add this. My concern is that a simple Q&A can turn into an entire Wikipedia page haha
            – Matías Fidemraizer
            Sep 6 '15 at 11:17










          • I see. Anyway if someone sees my comment, he'll have a basic idea of what I mean.
            – elad.chen
            Sep 6 '15 at 11:19


















          up vote
          1
          down vote













          When you're using for (var key in obj) it will loop through the given object + its parent objects' properties on the prototype chain until it reaches the end of the chain. As you want to check only specific object's properties, you need to use hasOwnProperty.



          This is not needed in for (var i = 0; i < length; i++) or data.forEach()






          share|improve this answer




























            up vote
            1
            down vote













            hasOwnProperty expects the property name as a string.



            When you call Test.hasOwnProperty(name) you are passing it the value of the name variable (which doesn't exist), just as it would if you wrote alert(name).



            Every object descended from Object inherits the hasOwnPropertymethod. This method can be used to determine whether an object has the specified property as a direct property of that object;



            Thanks






            share|improve this answer





















              Your Answer






              StackExchange.ifUsing("editor", function () {
              StackExchange.using("externalEditor", function () {
              StackExchange.using("snippets", function () {
              StackExchange.snippets.init();
              });
              });
              }, "code-snippets");

              StackExchange.ready(function() {
              var channelOptions = {
              tags: "".split(" "),
              id: "1"
              };
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function() {
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled) {
              StackExchange.using("snippets", function() {
              createEditor();
              });
              }
              else {
              createEditor();
              }
              });

              function createEditor() {
              StackExchange.prepareEditor({
              heartbeatType: 'answer',
              convertImagesToLinks: true,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: 10,
              bindNavPrevention: true,
              postfix: "",
              imageUploader: {
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              },
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              });


              }
              });














              draft saved

              draft discarded


















              StackExchange.ready(
              function () {
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f32422867%2fwhen-do-i-need-to-use-hasownproperty%23new-answer', 'question_page');
              }
              );

              Post as a guest















              Required, but never shown

























              3 Answers
              3






              active

              oldest

              votes








              3 Answers
              3






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes








              up vote
              22
              down vote



              accepted










              Object.hasOwnProperty determines if the whole property is defined in the object itself or in the prototype chain.



              In other words: do the so-called check if you want properties (either with data or functions) coming from no other place than the object itself.



              For example:



              function A() {
              this.x = "I'm an own property";
              }

              A.prototype.y = "I'm not an own property";

              var instance = new A();
              var xIsOwnProperty = instance.hasOwnProperty("x"); // true
              var yIsOwnProperty = instance.hasOwnProperty("y"); // false


              Do you want to avoid the whole check if you want own properties only?



              Since ECMA-Script 5.x, Object has a new function Object.keys which returns an array of string where its items are the own properties from a given object:



              var instance = new A();
              // This won't contain "y" since it's in the prototype so
              // it's not an "own object property"
              var ownPropertyNames = Object.keys(instance);


              Also, since ECMA-Script 5.x, Array.prototype has Array.prototype.forEach which lets perform a for-each loop fluently:



              Object.keys(instance).forEach(function(ownPropertyName) {
              // This function will be called for each found "own property", and
              // you don't need to do the instance.hasOwnProperty check anymore
              });





              share|improve this answer























              • Great example !
                – elad.chen
                Sep 6 '15 at 11:15










              • @elad.chen Thanks ;P Simple but still efficient!
                – Matías Fidemraizer
                Sep 6 '15 at 11:15










              • I would consider adding the usage of Object.keys(obj).forEach(..); As this will prevent prototype lookups..
                – elad.chen
                Sep 6 '15 at 11:17












              • @elad.chen Right, I can add this. My concern is that a simple Q&A can turn into an entire Wikipedia page haha
                – Matías Fidemraizer
                Sep 6 '15 at 11:17










              • I see. Anyway if someone sees my comment, he'll have a basic idea of what I mean.
                – elad.chen
                Sep 6 '15 at 11:19















              up vote
              22
              down vote



              accepted










              Object.hasOwnProperty determines if the whole property is defined in the object itself or in the prototype chain.



              In other words: do the so-called check if you want properties (either with data or functions) coming from no other place than the object itself.



              For example:



              function A() {
              this.x = "I'm an own property";
              }

              A.prototype.y = "I'm not an own property";

              var instance = new A();
              var xIsOwnProperty = instance.hasOwnProperty("x"); // true
              var yIsOwnProperty = instance.hasOwnProperty("y"); // false


              Do you want to avoid the whole check if you want own properties only?



              Since ECMA-Script 5.x, Object has a new function Object.keys which returns an array of string where its items are the own properties from a given object:



              var instance = new A();
              // This won't contain "y" since it's in the prototype so
              // it's not an "own object property"
              var ownPropertyNames = Object.keys(instance);


              Also, since ECMA-Script 5.x, Array.prototype has Array.prototype.forEach which lets perform a for-each loop fluently:



              Object.keys(instance).forEach(function(ownPropertyName) {
              // This function will be called for each found "own property", and
              // you don't need to do the instance.hasOwnProperty check anymore
              });





              share|improve this answer























              • Great example !
                – elad.chen
                Sep 6 '15 at 11:15










              • @elad.chen Thanks ;P Simple but still efficient!
                – Matías Fidemraizer
                Sep 6 '15 at 11:15










              • I would consider adding the usage of Object.keys(obj).forEach(..); As this will prevent prototype lookups..
                – elad.chen
                Sep 6 '15 at 11:17












              • @elad.chen Right, I can add this. My concern is that a simple Q&A can turn into an entire Wikipedia page haha
                – Matías Fidemraizer
                Sep 6 '15 at 11:17










              • I see. Anyway if someone sees my comment, he'll have a basic idea of what I mean.
                – elad.chen
                Sep 6 '15 at 11:19













              up vote
              22
              down vote



              accepted







              up vote
              22
              down vote



              accepted






              Object.hasOwnProperty determines if the whole property is defined in the object itself or in the prototype chain.



              In other words: do the so-called check if you want properties (either with data or functions) coming from no other place than the object itself.



              For example:



              function A() {
              this.x = "I'm an own property";
              }

              A.prototype.y = "I'm not an own property";

              var instance = new A();
              var xIsOwnProperty = instance.hasOwnProperty("x"); // true
              var yIsOwnProperty = instance.hasOwnProperty("y"); // false


              Do you want to avoid the whole check if you want own properties only?



              Since ECMA-Script 5.x, Object has a new function Object.keys which returns an array of string where its items are the own properties from a given object:



              var instance = new A();
              // This won't contain "y" since it's in the prototype so
              // it's not an "own object property"
              var ownPropertyNames = Object.keys(instance);


              Also, since ECMA-Script 5.x, Array.prototype has Array.prototype.forEach which lets perform a for-each loop fluently:



              Object.keys(instance).forEach(function(ownPropertyName) {
              // This function will be called for each found "own property", and
              // you don't need to do the instance.hasOwnProperty check anymore
              });





              share|improve this answer














              Object.hasOwnProperty determines if the whole property is defined in the object itself or in the prototype chain.



              In other words: do the so-called check if you want properties (either with data or functions) coming from no other place than the object itself.



              For example:



              function A() {
              this.x = "I'm an own property";
              }

              A.prototype.y = "I'm not an own property";

              var instance = new A();
              var xIsOwnProperty = instance.hasOwnProperty("x"); // true
              var yIsOwnProperty = instance.hasOwnProperty("y"); // false


              Do you want to avoid the whole check if you want own properties only?



              Since ECMA-Script 5.x, Object has a new function Object.keys which returns an array of string where its items are the own properties from a given object:



              var instance = new A();
              // This won't contain "y" since it's in the prototype so
              // it's not an "own object property"
              var ownPropertyNames = Object.keys(instance);


              Also, since ECMA-Script 5.x, Array.prototype has Array.prototype.forEach which lets perform a for-each loop fluently:



              Object.keys(instance).forEach(function(ownPropertyName) {
              // This function will be called for each found "own property", and
              // you don't need to do the instance.hasOwnProperty check anymore
              });






              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Sep 6 '15 at 11:21

























              answered Sep 6 '15 at 11:12









              Matías Fidemraizer

              48.5k1279146




              48.5k1279146












              • Great example !
                – elad.chen
                Sep 6 '15 at 11:15










              • @elad.chen Thanks ;P Simple but still efficient!
                – Matías Fidemraizer
                Sep 6 '15 at 11:15










              • I would consider adding the usage of Object.keys(obj).forEach(..); As this will prevent prototype lookups..
                – elad.chen
                Sep 6 '15 at 11:17












              • @elad.chen Right, I can add this. My concern is that a simple Q&A can turn into an entire Wikipedia page haha
                – Matías Fidemraizer
                Sep 6 '15 at 11:17










              • I see. Anyway if someone sees my comment, he'll have a basic idea of what I mean.
                – elad.chen
                Sep 6 '15 at 11:19


















              • Great example !
                – elad.chen
                Sep 6 '15 at 11:15










              • @elad.chen Thanks ;P Simple but still efficient!
                – Matías Fidemraizer
                Sep 6 '15 at 11:15










              • I would consider adding the usage of Object.keys(obj).forEach(..); As this will prevent prototype lookups..
                – elad.chen
                Sep 6 '15 at 11:17












              • @elad.chen Right, I can add this. My concern is that a simple Q&A can turn into an entire Wikipedia page haha
                – Matías Fidemraizer
                Sep 6 '15 at 11:17










              • I see. Anyway if someone sees my comment, he'll have a basic idea of what I mean.
                – elad.chen
                Sep 6 '15 at 11:19
















              Great example !
              – elad.chen
              Sep 6 '15 at 11:15




              Great example !
              – elad.chen
              Sep 6 '15 at 11:15












              @elad.chen Thanks ;P Simple but still efficient!
              – Matías Fidemraizer
              Sep 6 '15 at 11:15




              @elad.chen Thanks ;P Simple but still efficient!
              – Matías Fidemraizer
              Sep 6 '15 at 11:15












              I would consider adding the usage of Object.keys(obj).forEach(..); As this will prevent prototype lookups..
              – elad.chen
              Sep 6 '15 at 11:17






              I would consider adding the usage of Object.keys(obj).forEach(..); As this will prevent prototype lookups..
              – elad.chen
              Sep 6 '15 at 11:17














              @elad.chen Right, I can add this. My concern is that a simple Q&A can turn into an entire Wikipedia page haha
              – Matías Fidemraizer
              Sep 6 '15 at 11:17




              @elad.chen Right, I can add this. My concern is that a simple Q&A can turn into an entire Wikipedia page haha
              – Matías Fidemraizer
              Sep 6 '15 at 11:17












              I see. Anyway if someone sees my comment, he'll have a basic idea of what I mean.
              – elad.chen
              Sep 6 '15 at 11:19




              I see. Anyway if someone sees my comment, he'll have a basic idea of what I mean.
              – elad.chen
              Sep 6 '15 at 11:19












              up vote
              1
              down vote













              When you're using for (var key in obj) it will loop through the given object + its parent objects' properties on the prototype chain until it reaches the end of the chain. As you want to check only specific object's properties, you need to use hasOwnProperty.



              This is not needed in for (var i = 0; i < length; i++) or data.forEach()






              share|improve this answer

























                up vote
                1
                down vote













                When you're using for (var key in obj) it will loop through the given object + its parent objects' properties on the prototype chain until it reaches the end of the chain. As you want to check only specific object's properties, you need to use hasOwnProperty.



                This is not needed in for (var i = 0; i < length; i++) or data.forEach()






                share|improve this answer























                  up vote
                  1
                  down vote










                  up vote
                  1
                  down vote









                  When you're using for (var key in obj) it will loop through the given object + its parent objects' properties on the prototype chain until it reaches the end of the chain. As you want to check only specific object's properties, you need to use hasOwnProperty.



                  This is not needed in for (var i = 0; i < length; i++) or data.forEach()






                  share|improve this answer












                  When you're using for (var key in obj) it will loop through the given object + its parent objects' properties on the prototype chain until it reaches the end of the chain. As you want to check only specific object's properties, you need to use hasOwnProperty.



                  This is not needed in for (var i = 0; i < length; i++) or data.forEach()







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Sep 6 '15 at 11:14









                  Davion

                  756410




                  756410






















                      up vote
                      1
                      down vote













                      hasOwnProperty expects the property name as a string.



                      When you call Test.hasOwnProperty(name) you are passing it the value of the name variable (which doesn't exist), just as it would if you wrote alert(name).



                      Every object descended from Object inherits the hasOwnPropertymethod. This method can be used to determine whether an object has the specified property as a direct property of that object;



                      Thanks






                      share|improve this answer

























                        up vote
                        1
                        down vote













                        hasOwnProperty expects the property name as a string.



                        When you call Test.hasOwnProperty(name) you are passing it the value of the name variable (which doesn't exist), just as it would if you wrote alert(name).



                        Every object descended from Object inherits the hasOwnPropertymethod. This method can be used to determine whether an object has the specified property as a direct property of that object;



                        Thanks






                        share|improve this answer























                          up vote
                          1
                          down vote










                          up vote
                          1
                          down vote









                          hasOwnProperty expects the property name as a string.



                          When you call Test.hasOwnProperty(name) you are passing it the value of the name variable (which doesn't exist), just as it would if you wrote alert(name).



                          Every object descended from Object inherits the hasOwnPropertymethod. This method can be used to determine whether an object has the specified property as a direct property of that object;



                          Thanks






                          share|improve this answer












                          hasOwnProperty expects the property name as a string.



                          When you call Test.hasOwnProperty(name) you are passing it the value of the name variable (which doesn't exist), just as it would if you wrote alert(name).



                          Every object descended from Object inherits the hasOwnPropertymethod. This method can be used to determine whether an object has the specified property as a direct property of that object;



                          Thanks







                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Sep 6 '15 at 11:15









                          Anand Dwivedi

                          1,170821




                          1,170821






























                              draft saved

                              draft discarded




















































                              Thanks for contributing an answer to Stack Overflow!


                              • Please be sure to answer the question. Provide details and share your research!

                              But avoid



                              • Asking for help, clarification, or responding to other answers.

                              • Making statements based on opinion; back them up with references or personal experience.


                              To learn more, see our tips on writing great answers.





                              Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                              Please pay close attention to the following guidance:


                              • Please be sure to answer the question. Provide details and share your research!

                              But avoid



                              • Asking for help, clarification, or responding to other answers.

                              • Making statements based on opinion; back them up with references or personal experience.


                              To learn more, see our tips on writing great answers.




                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function () {
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f32422867%2fwhen-do-i-need-to-use-hasownproperty%23new-answer', 'question_page');
                              }
                              );

                              Post as a guest















                              Required, but never shown





















































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown

































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown







                              Popular posts from this blog

                              404 Error Contact Form 7 ajax form submitting

                              How to know if a Active Directory user can login interactively

                              Refactoring coordinates for Minecraft Pi buildings written in Python