Leran JavaScripts
JavaScript Object Protection
Using const
The most common way to protect an object from being changed is by using the const keyword.
With const you can not re-assign the object, but you can still change the value of a property, delete a property or create a new property.
JavaScript Object.preventExtensions()
The Object.preventExtensions() method prevents adding properties to an object.
// Create Object
const person = {firstName:"John", lastName:"Doe"};
// Prevent Extensions
Object.preventExtensions(person);
// This will throw an error
person.nationality = "English";
Arrays can be prevented from extensions too:
// Create Array
const fruits = ["Banana", "Orange", "Apple", "Mango"];
Object.preventExtensions(fruits);
// This will throw an error:
fruits.push("Kiwi");
JavaScript Object.isExtensible()
You can use Object.isExtensible() to check if an object is extensible.
The Object.isExtensible() returns true if an object is extensible.
// Create Object
const person = {firstName:"John", lastName:"Doe"};
// Prevent Extensions
Object.preventExtensions(person);
// This will return false
let answer = Object.isExtensible(person);
// Create Array
const fruits = ["Banana", "Orange", "Apple", "Mango"];
// Prevent Extensions
Object.preventExtensions(fruits);
// This will return false
let answer = Object.isExtensible(fruits);
With const you can not re-assign the object, but you can still change the value of a property, delete a property or create a new property.
JavaScript Object.preventExtensions()
The Object.preventExtensions() method prevents adding properties to an object.
// Create Object
const person = {firstName:"John", lastName:"Doe"};
// Prevent Extensions
Object.preventExtensions(person);
// This will throw an error
person.nationality = "English";
Arrays can be prevented from extensions too:
// Create Array
const fruits = ["Banana", "Orange", "Apple", "Mango"];
Object.preventExtensions(fruits);
// This will throw an error:
fruits.push("Kiwi");
JavaScript Object.isExtensible()
You can use Object.isExtensible() to check if an object is extensible.The Object.isExtensible() returns true if an object is extensible.
// Create Object
const person = {firstName:"John", lastName:"Doe"};
// Prevent Extensions
Object.preventExtensions(person);
// This will return false
let answer = Object.isExtensible(person);
// Create Array
const fruits = ["Banana", "Orange", "Apple", "Mango"];
// Prevent Extensions
Object.preventExtensions(fruits);
// This will return false
let answer = Object.isExtensible(fruits);