Predict the output of the following javascript code
const a = { a: 1 };
const b = Object.seal(a);
b.a = 2;
console.log(a.a);
Quiz Explanation
const a = { a: 1 };
: This line creates an objecta
with a propertya
set to the value1
.const b = Object.seal(a);
: Here, theObject.seal()
method is used to seal the objecta
. Sealing an object in JavaScript means that you can't add or remove properties from it, though you can still modify the existing properties. The sealed object is returned and assigned to variableb
.b.a = 2;
: This line attempts to modify the propertya
of the sealed objectb
to2
.console.log(a.a);
: Finally, this logs the value of propertya
of the original objecta
to the console.
Given that a
was sealed by Object.seal()
, modifying b.a
does affect the property a
of the original object a
.
So, when you run this code, it will output 2
, because the modification to b.a
is reflected in a.a
. Since a
was sealed, the modification is allowed.