Is it possible to make a javascript object property read-only? I want to set a property that cannot be modified...
It's possible, but expensive. You can do it by having a truly private member variable and then providing an accessor function:
var NiftyThing = function() {
var trulyPrivateVariable;
trulyPrivateVariable = 5; // For instance
this.accessorFunction = function() {
return trulyPrivateVariable;
}
};
That works because the accessor function is a closure over the var. The cost is that each instance has its own copy of the accessor function.
EDIT: Usage:
var n = new NiftyThing();
alert(n.trulyPrivateVariable);
// Alerts "undefined"
alert(n.accessorFunction());
// Alerts "5"
See Private Member Variables in JavaScript for more.
You can implement something like this, making use of Object.defineProperty():
function blockProperties(object, properties) {
"use strict";
// If not properties passed, then use the already defined ones:
if (typeof properties === "undefined") {
properties = object;
}
// Loop trough the properties
for (var property in properties) {
if (properties.hasOwnProperty(property)) {
// Make property read-only
Object.defineProperty(object, property, {
value: properties[property],
writable: false,
configurable: false,
enumerable: false
});
}
}
return object;
}
var someObject = {};
blockProperties(someObject, {
propertie1: "someValue",
propertie2: "someOtherValue"
});
someObject.propertie1 = "this doesn't change anything";
console.log(someObject.propertie1); // Output: "someValue"
// Because "window" is also an object, you can set an only-read global var:
blockProperties(window, {
onlyReadVariable: "onlyReadValue"
});
I agree with the answer, and would like to note that some JavaScript frameworks like bob.js support such built-in mechanisms:
var obj = { };
//declare read-only property.
bob.prop.namedProp(obj, 'name', 'Bob', true);
//declare read-write property.
bob.prop.namedProp(obj, 'age', 1);
//get values of properties.
console.log(bob.string.formatString('{0} is {1} years old.', obj.get_name(), obj.get_age()));
//set value of read-write property.
obj.set_age(2);
console.log(bob.string.formatString('Now {0} is {1} years old.', obj.get_name(), obj.get_age()));
//cannot set read-only property of obj. Next line would throw an error.
// obj.set_name('Rob');
//Output:
//========
// Bob is 1 years old.
// Now Bob is 2 years old.
However, if you have special needs regarding property, such as specific get accessor implementation needs, then better define a function which gets the value as you need it.
-
Tengiz
Related
Why can't I assign new properties to non-frozen object, which has frozen prototype:
Working without Object.freeze:
'use strict'
//This object will be prototype of next objects
var defaults = {
name: 'def name',
sections: {
1: {
secName: 'def sec name'
}
}
};
//So we have an empty object with prototype set to our default object.
var specificObject = Object.create(defaults);
specificObject.sections = {};
console.log(specificObject.hasOwnProperty('sections')); //true
specificObject.sections['1'] = Object.create(defaults.sections['1']);
Above code works as expected, but I want to make sure that defaults won't be accidentally changed. So I want to freeze my defaults object:
'use strict'
//This object will be prototype of next objects
var defaults = {
name: 'def name',
sections: {
1: {
secName: 'def sec name'
}
}
};
//!!!!!!!!!!!!
Object.freeze(defaults);
//So we have an empty object with prototype set to our default object.
var specificObject = Object.create(defaults);
//TypeError: Cannot assign to read only property 'sections' of #<Object>
specificObject.sections = {};
console.log(specificObject.hasOwnProperty('sections')); //true
specificObject.sections['1'] = Object.create(defaults.sections['1']);
What I don't get is why can't I assign to specificObject if its prototype is frozen?
//EDIT:
Notice that specific object is not frozen:
'use strict'
//This object will be prototype of next objects
var protoObj = {a: 1, o: {}};
Object.freeze(protoObj);
console.log(Object.isFrozen(protoObj)); //true
var n = Object.create(protoObj);
console.log(Object.isFrozen(n)); //false
What I don't get is why can't I assign to specificObject if its prototype is frozen?
Because property attributes are inherited. Yes, it's odd.
If you freeze an object, it will set the [[writable]] attribute of all data properties to false.
If you assign to an object property, but that property does not exist on the object, it will go and look it up on the prototype - it might be defined as setter there. When this lookup will return and say that there is a property of that name but it is non-writable, your assignment will fail (and throw in strict mode).
What can you do against this?
Use Object.defineProperty instead of assignment, it doesn't check the prototype
or similarly, use the second parameter of Object.create to create the own property
freeze the defaults only after you've assigned to specificObject.
my understanding is that specificObject.sections is pointing to its' prototype which is defaults and it is frozen object. You define a new object {} but you try to assign it to defaults.sections. SpecificObject.sections is pointing exactly there.
If you create new ownProperty on specificObject it will work:
'use strict'
//This object will be prototype of next objects
var defaults = {
name: 'def name',
sections: {
1: {
secName: 'def sec name'
}
}
};
//!!!!!!!!!!!!
Object.freeze(defaults);
//So we have an empty object with prototype set to our default object.
var specificObject = Object.create(defaults);
// this will create new property
Object.defineProperty(specificObject, 'sections',{
enumerable: true,
writable: true,
configurable: true,
value: {}
});
console.log(specificObject.hasOwnProperty('sections')); //true
specificObject.sections['1'] = Object.create(defaults.sections['1']);
explanation:
if you try to access obj.prop = val then javascript looks into obj's own properties, if not found then it looks into obj's prototype own properties. if found there then it /tries to assign val to/ lookup that property. if not found there then it tries to look into obj's prototype's prototype and so on. If prop is not found in the prototype tree then it creates new own property on obj and assigns val.
Therefore if prop is find on prototype and it is frozen you will get type error. Hope it brings some light.:)
EDIT:
as correctly pointed out by #KubaWyrostek specificObj.sections = {} will create new own property of specific Object, does not assign new value to the prototype's property, but it probably does the lookup for the property to check the writability, in that case it will run into frozen object. I didn't know about this before.
in following code I declare two objects of class "person".
problem is that when for one of the variables ("Courses") I use push method to update its values so they are copied in proto and as a consequence both objects share same "Courses" array inside there proto. i want them to have there own unique arrays.
var person = {
Name: "John",
Grade: 0,
Courses:[],
setGrade : function(y){
this.Grade=y;
},
setCourse:function(t){
this.Courses.push(t);
},
}
var grade9 = Object.create(person);
grade9.setCourse("eng");
grade9.setCourse("math");
grade9.setGrade(9);
var grade10 = Object.create(person);
grade10.setCourse("phy");
grade10.setCourse("chem");
grade10.setCourse("bio");
grade10.setGrade(10);
debug output
thanx.
Create a factory method, and inside overshadow the property with a specific property for the current instance:
function createNewPerson() {
return Object.create(person, { // object.create with propertiesObject to overshadow original Courses property
Courses: { writable: true, configurable: true, value: [] }
});
}
var grade9 = createNewPerson();
grade9.setCourse("eng");
grade9.setCourse("math");
grade9.setGrade(9);
var grade10 = createNewPerson();
grade10.setCourse("phy");
grade10.setCourse("chem");
grade10.setCourse("bio");
grade10.setGrade(10);
Object.create returns an object with the prototype property set to the passed-in object. The 'instance' objects delegate to the prototype. The same prototype. In C terms they all have pointers to the same struct (the prototype) and modifying it changes the value for all the 'instance' objects (they're only pointing to it). While that isn't totally accurate its enough so for our purposes here. If you want them to all to have independent copies you'll have to add them:
personFactory = function() {
newPerson = Object.create(person);
newPerson.array = [];
}
myPerson = personFactory();
I have a problem I can't solved because I can't explain this behaviour :
var A = function(value) {
this.prop = value;
};
A.prototype = {
prop: 0
};
var a = new A(1);
var b = new A(2);
console.log(a.prop);
console.log(b.prop);
output :
1
2
But, with this code (almost the same) :
var A = function(value) {
this.prop.value = value;
};
A.prototype = {
prop: {
value: 0
}
};
var a = new A(1);
var b = new A(2);
console.log(a.prop.value);
console.log(b.prop.value);
I have this output :
2
2
Can anybody explain me this ?
Thanks...
EDIT :
Here's a solution :
var A = function(value) {
this.prop = {};
this.prop.value = value;
};
A.prototype = {
};
var a = new A(1);
var b = new A(2);
console.log(a.prop.value);
console.log(b.prop.value);
In example 1, this.prop is a primitive type, which is referenced by value and thus not shared between instances.
In example 2, this.prop is an Object whose reference is initialized from the prototype from a single object, so this single object is shared by all instances.
In the last "example" solution, you create a new object with = {}, so all instances now have their own object.
More details about primitive types : Primitive value vs Reference value
prototype is created only once and it's only a simple object whose childs are attached for all instances of a function it belongs to.
So it's basically the same as if you write:
var obj = { value: 0 };
var a = {}, b = {};
a.obj = obj;
b.obj = obj;
obj.value = 2;
as you can see both a.obj and b.obj references to the same obj and both a.obj.value and b.obj.value will be 2 in this example
This is happening because in JS, objects are passed by reference, while primitives are not.
Since the prototype is shared between the 2 instances, modifying a object on it will update all instances.
Think of a prototype property as a property shared amongst all instances.
Yet you can override it on each instance, that 's what you do in the first example.
Once overriden in each instance, you do not access any more to the prototype property with obj.prop, which now refers to the instance property. You would need to use obj.prototype.prop to read it again, but this syntax is illegal : you can use obj.__proto__.prop (non standard) or Object.getPrototypeOf(obj).prop (EcmaScript 5) to do so.
In the second instance, you do not change the property in the constructor : rather you change a property of this property. So both constructor access to the very same object, then change one of its property value, so the last to set it will 'win'. Here the prototype property is not overriden ('hidden') by the instance property and accessing obj.prop in fact access 'obj.prototype.prop'.
I am checking for the existence of an object property with a variable holding the property name in question.
var myObj;
myObj.prop = "exists";
var myProp = "p"+"r"+"o"+"p";
if(myObj.myProp){
alert("yes, i have that property");
};
This is undefined because it's looking for myObj.myProp but I want it to check for myObj.prop
var myProp = 'prop';
if(myObj.hasOwnProperty(myProp)){
alert("yes, i have that property");
}
Or
var myProp = 'prop';
if(myProp in myObj){
alert("yes, i have that property");
}
Or
if('prop' in myObj){
alert("yes, i have that property");
}
Note that hasOwnProperty doesn't check for inherited properties, whereas in does. For example 'constructor' in myObj is true, but myObj.hasOwnProperty('constructor') is not.
You can use hasOwnProperty, but based on the reference you need quotes when using this method:
if (myObj.hasOwnProperty('myProp')) {
// do something
}
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty
Another way is to use in operator, but you need quotes here as well:
if ('myProp' in myObj) {
// do something
}
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in
Thank you for everyone's assistance and pushing to get rid of the eval statement.
Variables needed to be in brackets, not dot notation. This works and is clean, proper code.
Each of these are variables: appChoice, underI, underObstr.
if(typeof tData.tonicdata[appChoice][underI][underObstr] !== "undefined"){
//enter code here
}
For own property :
var loan = { amount: 150 };
if(Object.prototype.hasOwnProperty.call(loan, "amount"))
{
//will execute
}
Note: using Object.prototype.hasOwnProperty is better than loan.hasOwnProperty(..), in case a custom hasOwnProperty is defined in the prototype chain (which is not the case here), like
var foo = {
hasOwnProperty: function() {
return false;
},
bar: 'Here be dragons'
};
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty
To include inherited properties in the finding use the in operator: (but you must place an object at the right side of 'in', primitive values will throw error, e.g. 'length' in 'home' will throw error, but 'length' in new String('home') won't)
const yoshi = { skulk: true };
const hattori = { sneak: true };
const kuma = { creep: true };
if ("skulk" in yoshi)
console.log("Yoshi can skulk");
if (!("sneak" in yoshi))
console.log("Yoshi cannot sneak");
if (!("creep" in yoshi))
console.log("Yoshi cannot creep");
Object.setPrototypeOf(yoshi, hattori);
if ("sneak" in yoshi)
console.log("Yoshi can now sneak");
if (!("creep" in hattori))
console.log("Hattori cannot creep");
Object.setPrototypeOf(hattori, kuma);
if ("creep" in hattori)
console.log("Hattori can now creep");
if ("creep" in yoshi)
console.log("Yoshi can also creep");
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in
Note: One may be tempted to use typeof and [ ] property accessor as the following code which doesn't work always ...
var loan = { amount: 150 };
loan.installment = undefined;
if("installment" in loan) // correct
{
// will execute
}
if(typeof loan["installment"] !== "undefined") // incorrect
{
// will not execute
}
A much more secure way to check if property exists on the object is to use empty object or object prototype to call hasOwnProperty()
var foo = {
hasOwnProperty: function() {
return false;
},
bar: 'Here be dragons'
};
foo.hasOwnProperty('bar'); // always returns false
// Use another Object's hasOwnProperty and call it with 'this' set to foo
({}).hasOwnProperty.call(foo, 'bar'); // true
// It's also possible to use the hasOwnProperty property from the Object
// prototype for this purpose
Object.prototype.hasOwnProperty.call(foo, 'bar'); // true
Reference from MDN Web Docs - Object.prototype.hasOwnProperty()
there are much simpler solutions and I don't see any answer to your actual question:
"it's looking for myObj.myProp but I want it to check for myObj.prop"
to obtain a property value from a variable, use bracket notation.
to test that property for truthy values, use optional
chaining
to return a boolean, use double-not / bang-bang / (!!)
use the in operator if you are certain you have an object and only want to check for the existence of the property (true even if prop value is undefined). or perhaps combine with nullish coalescing operator ?? to avoid errors being thrown.
var nothing = undefined;
var obj = {prop:"hello world"}
var myProp = "prop";
consolelog( 1,()=> obj.myProp); // obj does not have a "myProp"
consolelog( 2,()=> obj[myProp]); // brackets works
consolelog( 3,()=> nothing[myProp]); // throws if not an object
consolelog( 4,()=> obj?.[myProp]); // optional chaining very nice ⭐️⭐️⭐️⭐️⭐️
consolelog( 5,()=> nothing?.[myProp]); // optional chaining avoids throwing
consolelog( 6,()=> nothing?.[nothing]); // even here it is error-safe
consolelog( 7,()=> !!obj?.[myProp]); // double-not yields true
consolelog( 8,()=> !!nothing?.[myProp]); // false because undefined
consolelog( 9,()=> myProp in obj); // in operator works
consolelog(10,()=> myProp in nothing); // throws if not an object
consolelog(11,()=> myProp in (nothing ?? {})); // safe from throwing
consolelog(12,()=> myProp in {prop:undefined}); // true (prop key exists even though its value undefined)
// beware of 'hasOwnProperty' pitfalls
// it can't detect inherited properties and 'hasOwnProperty' is itself inherited
// also comparatively verbose
consolelog(13,()=> obj.hasOwnProperty("hasOwnProperty")); // DANGER: it yields false
consolelog(14,()=> nothing.hasOwnProperty("hasOwnProperty")); // throws when undefined
obj.hasOwnProperty = ()=>true; // someone could overwrite it
consolelog(15,()=> obj.hasOwnProperty(nothing)); // DANGER: the foolish overwrite will now always return true
consolelog(16,()=> Object.prototype.hasOwnProperty.call(obj,"hasOwnProperty")); //😭 explain?!
consolelog(17,()=> Object.hasOwn(obj,"hasOwnProperty")); //😭 explain?!
function consolelog(num,myTest){
try{
console.log(num,myTest());
}
catch(e){
console.log(num,'throws',e.message);
}
}
You can use hasOwnProperty() as well as in operator.
Using the new Object.hasOwn method is another alternative and it's intention is to replace the Object.hasOwnProperty method.
This static method returns true if the specified object has the indicated property as its own property or false if the property is inherited or does not exist on that object.
Please not that you must check the Browser compatibility table carefully before using this in production since it's still considered an experimental technology and is not fully supported yet by all browsers (soon to be though)
var myObj = {};
myObj.myProp = "exists";
if (Object.hasOwn(myObj, 'myProp')){
alert("yes, i have that property");
}
More about Object.hasOwn - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwn
Object.hasOwn browser compatibility - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwn#browser_compatibility
Several ways to check if an object property exists.
const dog = { name: "Spot" }
if (dog.name) console.log("Yay 1"); // Prints.
if (dog.sex) console.log("Yay 2"); // Doesn't print.
if ("name" in dog) console.log("Yay 3"); // Prints.
if ("sex" in dog) console.log("Yay 4"); // Doesn't print.
if (dog.hasOwnProperty("name")) console.log("Yay 5"); // Prints.
if (dog.hasOwnProperty("sex")) console.log("Yay 6"); // Doesn't print, but prints undefined.
Working for me.
if (typeof receviedData?.d?.heartbeat_interval != "undefined") {
}
In the answers I didn't see the !! truthiness check.
if (!!myObj.myProp) //Do something
Consider:
if (someVar.hasOwnProperty('someProperty') ) {
// Do something();
} else {
// Do somethingElse();
}
What is the right use/explanation of hasOwnProperty('someProperty')?
Why can't we simply use someVar.someProperty to check if an object someVar contains property with name someProperty?
What is a property in this case?
What property does this JavaScript check?
hasOwnProperty returns a boolean value indicating whether the object on which you are calling it has a property with the name of the argument. For example:
var x = {
y: 10
};
console.log(x.hasOwnProperty("y")); //true
console.log(x.hasOwnProperty("z")); //false
However, it does not look at the prototype chain of the object.
It's useful to use it when you enumerate the properties of an object with the for...in construct.
If you want to see the full details, the ES5 specification is, as always, a good place to look.
Here is a short and precise answer:
In JavaScript, every object has a bunch of built-in key-value pairs that have meta information about the object. When you loop through all the key-value pairs using for...in construct/loop for an object you're looping through this meta-information key-value pairs too (which you definitely don't want).
Using hasOwnPropery(property) filters-out these unnecessary looping through meta information and directly checks that is the parameter property is a user-given property in the object or not.
By filters-out, I mean, that hasOwnProperty(property) does not look if, property exists in Object's prototype chain aka meta information.
It returns boolean true/false based on that.
Here is an example:
var fruitObject = {"name": "Apple", "shape": "round", "taste": "sweet"};
console.log(fruitObject.hasOwnProperty("name")); //true
console.log(Object.prototype.hasOwnProperty("toString")) // true because in above snapshot you can see, that there is a function toString in meta-information
I hope it's clear!
It checks:
Returns a Boolean value indicating whether an object has a property with the specified name
The hasOwnProperty method returns true if the object has a property of the specified name, false if it does not. This method does not check if the property exists in the object's prototype chain; the property must be a member of the object itself.
Example:
var s = new String("Sample");
document.write(s.hasOwnProperty("split")); //false
document.write(String.prototype.hasOwnProperty("split")); //true
Summary:
hasOwnProperty() is a function which can be called on any object and takes a string as an input. It returns a boolean which is true if the property is located on the object, otherwise it returns false. hasOwnProperty() is located on Object.prototype and thus available for any object.
Example:
function Person(name) {
this.name = name;
}
Person.prototype.age = 25;
const willem = new Person('willem');
console.log(willem.name); // Property found on object
console.log(willem.age); // Property found on prototype
console.log(willem.hasOwnProperty('name')); // 'name' is on the object itself
console.log(willem.hasOwnProperty('age')); // 'age' is not on the object itself
In this example a new Person object is created. Each Person has its own name which gets initialized in the constructor. However, the age is not located on the object but on the prototype of the object. Therefore hasOwnProperty() does return true for name and false for age.
Practical applications:
hasOwnProperty() can be very useful when looping over an object using a for in loop. You can check with it if the properties are from the object itself and not the prototype. For example:
function Person(name, city) {
this.name = name;
this.city = city;
}
Person.prototype.age = 25;
const willem = new Person('Willem', 'Groningen');
for (let trait in willem) {
console.log(trait, willem[trait]); // This loops through all properties, including the prototype
}
console.log('\n');
for (let trait in willem) {
if (willem.hasOwnProperty(trait)) { // This loops only through 'own' properties of the object
console.log(trait, willem[trait]);
}
}
You use object.hasOwnProperty(p) to determine if an object has an enumerable property p-
An object can have its own prototype, where 'default' methods and attributes are assigned to every instance of the object. hasOwnProperty returns true only for the properties that were specifically set in the constructor, or added to the instance later.
To determine if p is defined at all, anywhere, for the object, use if(p instanceof object), where p evaluates to a property-name string.
For example, by default all objects have a 'toString' method, but it will not show up in hasOwnProperty.
hasOwnProperty is a proper way of checking an object has a property or not. someVar.someProperty cannot be used as an alternative to this situation. The following condition will show a good difference:
const someVar = { isFirst: false };
// The condition is true, because 'someVar' has property 'isFirst'
if (someVar.hasOwnProperty('isFirst')) {
// Code runs
}
// The condition is false, because 'isFirst' is false.
if (someVar.isFirst) {
// Code does not runs here
}
Hence someVar.isFirst cannot be used alternative to someVar.hasOwnProperty('isFirst').
hasOwnProperty is a normal JavaScript function that takes a string argument.
In your case, somevar.hasOwnProperty('someProperty'), it checks the somevar function has somepropery or not - it returns true and false.
Say
function somevar() {
this.someProperty = "Generic";
}
function welcomeMessage()
{
var somevar1 = new somevar();
if(somevar1.hasOwnProperty("name"))
{
alert(somevar1.hasOwnProperty("name")); // It will return true
}
}
2021 - Object.hasOwn as a replacement for Object.hasOwnProperty()
As other answers indicated, hasOwnProperty will check for an object own properties in contrast to in which will also check for inherited properties.
There is a new alternative method called Object.hasOwn() and is intended to be a replacement for Object.hasOwnProperty()**
Object.hasOwn() is a static method which returns true if the specified object has the specified property as its own property. If the property is inherited, or does not exist, the method returns false.
const person = { name: 'dan' };
console.log(Object.hasOwn(person, 'name'));// true
console.log(Object.hasOwn(person, 'age'));// false
const person2 = Object.create({gender: 'male'});
console.log(Object.hasOwn(person2, 'gender'));// false
It is recommended to this method use over the Object.hasOwnProperty() because it also works for objects created by using Object.create(null) and for objects that have overridden the inherited hasOwnProperty() method. Although it's possible to solve these kind of problems by calling Object.prototype.hasOwnProperty() on an external object, Object.hasOwn() overcome these problems, hence is preferred (see examples below)
let person = {
hasOwnProperty: function() {
return false;
},
age: 35
};
if (Object.hasOwn(person, 'age')) {
console.log(person.age); // true - the remplementation of hasOwnProperty() did not affect the Object
}
let person = Object.create(null);
person.age = 35;
if (Object.hasOwn(person, 'age')) {
console.log(person.age); // true - works regardless of how the object was created
}
More about Object.hasOwn can be found here : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwn
Browser compatibility - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwn#browser_compatibility
What is the right use/explanation of hasOwnProperty('someProperty') ?
The hasOwnProperty() method returns a boolean indicating whether the object has the specified property as its own property (as opposed to inheriting it).
const someVar = {};
someVar.someProperty = 'Foo';
console.log(someVar.hasOwnProperty('someProperty'));
// expected output: true
console.log(someVar.hasOwnProperty('someProperty1'));
// expected output: false
Why can't we simply use someVar.someProperty to check if an object someVar contains property with name someProperty ?
someVar.someProperty will return the property value, You can not check that this property is available in the object or not via someVar.someProperty.
Now in ES2022, A new method has been introduced which is Object.hasOwn(<object reference>, <property name>) this method is intended as a replacement for Object.hasOwnProperty() which overcome some limitations of .hasOwnProperty().
Scene A:
const objA = { a: 1, b: 2 }
for (const key in objA) {
if (objA.hasOwnProperty(key)) {
console.log(objA[key])
}
}
Output
1
2
Scene B:
const objB = {
a: 1,
b: 2,
hasOwnProperty() {
return false
}
}
for (const key in objB) {
if (objB.hasOwnProperty(key)) {
console.log(objB[key])
}
}
Outputs nothing
Because JavaScript doesn't protect the property of hasOwnProperty.
So you can use it like this:
for (const key in objB) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
console.log(objB[key])
}
}
It checks if an object has a property. It works the same as if(obj.prop), as far as I know.