Javascript : Check if object has properties [duplicate] - javascript

This question already has answers here:
if (key in object) or if(object.hasOwnProperty(key)
(9 answers)
Closed 8 years ago.
There are several answers here how to check if a property exists in an object.
I was always using
if(myObj.hasOwnProperty('propName'))
but I wonder if there is any difference from
if('propName' in myObj){

They are almost equal, the difference is that hasOwnProperty does not check down the prototype chain, while in does.
An example
var test = function() {}
test.prototype.newProp = function() {}
var instance = new test();
instance.hasOwnProperty('newProp'); // false
'newProp' in instance // true
FIDDLE
As noted, Object.hasOwnProperty only returns "own properties", i.e. properties that are added directly, and not properties added to the prototype.

Yes, there is difference. hasOwnProperty() ignores properties and methods which are added with prototype. I try to explain with examples. For instance if you have prototype of object
Object.prototype.something = function() {};
And let's say you have following object
var obj = {
"a" : "one",
"b" : "two"
};
And loop:
for ( var i in obj ) {
//if (obj.hasOwnProperty(i)) {
console.log(obj[i]);
//}
}
Without hasOwnProperty it will output one two function(), while with hasOwnProperty() method only one two
See the differences between First and Second DEMOS

Related

Can Array.isArray be tricked? [duplicate]

This question already has answers here:
Can you fake out Array.isArray() with a user-defined object?
(2 answers)
Closed 1 year ago.
I understand the concept of prototypes very well; so when I tried this, I was confused at first:
var obj = {};
Object.setPrototypeOf(obj, Array.prototype);
console.log(Array.isArray(obj)); // false?
Even scarier:
var arr = [];
Object.setPrototypeOf(arr, Object.prototype);
console.log(Array.isArray(arr)); // true?? 8-{
Until I did my research and found that Array.isArray looks for a hidden property of the object: [[DefineOwnProperty]].
Is this something that is completely immutable on an existing object? Or could a plain object {} be mutated such that calling Array.isArray on it would return true?
No, Array.isArray cannot be tricked.
And there's no way to change an object between an array and non-array. Just like you cannot change the callability of a function object, not even through the target of a proxy object.

Why do I need to bind a shadowed function that is called through the same object? [duplicate]

This question already has answers here:
How does the "this" keyword in Javascript act within an object literal? [duplicate]
(4 answers)
Closed 4 years ago.
Was doing some dirty things to Array.prototype when I ran into this:
Array.prototype.hook_pop = function(callback) {
var base_pop = this.pop.bind(this); //<-- this works
var base_pop = this.pop; //<-- this doesn't work
this.pop = function() {
var ret = base_pop();
callback(ret, this);
return ret;
}
}
Initially I tried using the non-working option and got an error "Uncaught TypeError: Cannot convert undefined or null to object".
The way I've understood it, unless otherwise bound, "this" should point to the object through which the method is called from, in this case the array instance. When called on the same object though, either way, "this" should be the same when being passed to the pop function, whether its bound or not. Why doesn't the second option work?
var ret = base_pop();
In this line you're invoking base_pop() by itself, and not as a method of any object. Because of this, its this value isn't set.

Where does the Array.prototype functions come from? [duplicate]

This question already has answers here:
Why does Array.prototype return an empty array?
(2 answers)
Closed 6 years ago.
Since Array.prototype itself returns an empty array, where do all functions come from?
Why I can call functions something like Array.prototype.sort, even Array.prototype is not object?
Array.prototype.__proto__ is an object.
I have same question on the case of Function.prototype.
Array.prototype is an object, and most functions you used for array come from it. So it's the prototype.
Open chrome dev bar, and check it like the below image.
even Array.prototype is not object?
How did you get that idea? It is an object:
typeof Array.prototype // "object"
As such it can have properties like every other object. And it does:
Array.prototype.hasOwnProperty("sort") // true
Array.prototype.sort // function(compare) { … }
This is the same for every other array, you can create custom properties on them like on every javascript object:
var foo = [];
foo.bar = "baz";
typeof foo.bar // "string"
Array.isArray(foo) // true

Different ways of defining unassign variable in javascript [duplicate]

This question already has answers here:
How do I test for an empty JavaScript object?
(48 answers)
Closed 6 years ago.
I know when we want to define unassign variable in Javascript we can do:
var p;
and the other:
var p ={};
i want to know differences between these two ways, and if i define a variable in second way it is not null! what is the value in the variable, if we want using it in a if condition, for example :
var p ={};
if(p=='what i shout put there')
{}
var p is creating an unassigned variable. So console.log(p) will log undefined
var p ={}; is a way of creating object using literal notation.
Object p have methods like constructor,hasOwnProperty,toLocaleString etc
if(p=='what i shout put there'){}
If it is required to check if p is an object then below snippet is useful
if(Object.prototype.toString.call( a ) === '[object Object]'){
// Do rest of code
}
An object can have properties. like
var p={};
p.a ="someValue";
In this case you can check by
if(p.a === 'someValue'){
// Do rest of code
}
var p = {};
It is not unassigned ,it is infact assigned to the empty object
If you do below , it will be trut
if(p) {} // truthy

why comparing empty object directly showing false? [duplicate]

This question already has answers here:
How to determine equality for two JavaScript objects?
(82 answers)
Closed 7 years ago.
I was checking in my console. When i checked empty object directly like {} == {} , it show false.
Why it's showing false ? shouldn't it show true as both are equal ?
When i checked empty object directly like {} == {} , it show false.
You have two different objects here and not one. Here == checks whether the given two objects are same or not.
Scenario 1:
var foo = {}; //new object
var bar = foo; //shared same object
foo == bar;// true
Scenario 2:
var foo = {}; //new object
var bar = {}; //new object
foo == bar;// false
If you still wish to compare two different objects, try this:
var foo = {}; //new object
var bar = {}; //new object
JSON.stringify(foo) == JSON.stringify(bar);// true
Here, JSON.stringify({}) gives string value "{}"
Both are NOT equal. Although they are empty, both refers to different objects.
Primitives like strings and numbers are compared by their value, while objects like arrays, dates, and plain objects are compared by their reference. That comparison by reference basically checks to see if the objects given refer to the same location in memory, which they do not, so the comparison is false.

Categories