Skip to main content
Inspiring
January 30, 2019
Question

Problems with .hasOwnProperty

  • January 30, 2019
  • 2 replies
  • 1427 views

Hello

I have a problem with a JavaScript method : hasOwnProperty.

I want to test this property and ESTK don't work correctly.

My little code :

//------------

alert(1)

if(Array.prototype.hasOwnProperty("push")){

    alert("hello)

}

alert(2)

//------------

Normally, I have 3 alerts (1, "hello" and 2) but ESTK send me 2 alerts only (1 and 2).

ESTK send me false for condition if.

I share with you a Youtube video : hasOwnProperty - YouTube

I tried on development console and Google send me 3 alerts (1, "hello", 2).

Sometimes, ESTK send me true for condition only if I changed argument "push" to "pop" or "push" to "join" before, for example.

Can you help me for this problem, thank you.

This topic has been closed for replies.

2 replies

Silly-V
Legend
January 31, 2019

hasOwnProperty is only going to find properties that belong to an instance of an object, but not the prototypes or any class-owned properties.

See the test below: you can check typeof() to see if the item in question is a function, another datatype, or undefined.

    var arr = [1,2,3];

    alert(arr.hasOwnProperty("push")); // false

    alert(arr.hasOwnProperty("0")); // true

    alert(arr.hasOwnProperty("4")); // false

   

    alert(typeof(Array.prototype.push)); // function

    alert(typeof(Array.prototype.donaldDuck)); // undefined

Inspiring
February 5, 2019

Ok but if Object.prototype have hasOwnProperty method, it's strange I can't use it for build-in object, no ?

Silly-V
Legend
February 6, 2019

Well, in that case it's probably differences between the ES3 and ES5 javascripts.

Probably in ES3 they didn't have the prototype object souped-up like in our modern-day browsers!

EcmaScript 3 VS EcmaScript 5 - Jie Huang's Blog

CarlosCanto
Community Expert
Community Expert
January 31, 2019

what are you trying to achieve?

you suppose to use the "hasOwnProperty" function on objects you create yourself

for example

var myArray = [1, 2, 3];

myArray.id = 10;

alert(myArray.hasOwnProperty("id"));

Inspiring
February 5, 2019

Hello, sorry for late and thank you for your answer

I want just know why hasOwnProperty don't work correctly on ESTK but yes in Chrome

CarlosCanto
Community Expert
Community Expert
February 6, 2019

oh ok