Immutable Objects in Javascript

let name = {
firstName: "Virender",
lastName: "Sehwag",
getFullName() {
return firstName + " " + lastName;
},
};
const arr = [1,2,3];
arr[3] = 4;
console.log(arr); // [1,2,3,4];

const obj = {firstName="Virat"}
obj.lastName = "Kohli";
console.log(obj); // {firstName="Virat", lastName="Kohli"}

Object.freeze()

let name = {
firstName: "Virender",
lastName: "Sehwag",
getFullName() {
return firstName + " " + lastName;
},
};
Object.freeze(name);name.middleName = "R"; // !!!ERROR!!! in strict mode
name.firstName = "Sachin"; // ERROR!!! in strict mode
Object.isFrozen(name);    // true

Object.seal()

let name = {
firstName: "Virender",
lastName: "Sehwag",
getFullName() {
return firstName + " " + lastName;
},
};
Object.seal(name);name.middleName = "R"; // ERROR!!! in strict mode
name.firstName = "Sachin"; // Works!!!
delete name.lastName; // ERROR!!! in strict mode
Object.isSealed(name);   // true

Object.preventExtension()

let name = {
firstName: "Jasprit",
lastName: "Bumrah",
getFullName() {
return firstName + " " + lastName;
},
};
Object.preventExtesion(name);name.middleName = "R"; // ERROR!!! in strict mode
name.firstName = "Sachin"; // Works!!!
delete name.lastName // true
Object.isExtensible(name);    // false

--

--

--

Full stack developer

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

How to use Rechart in React

How to Build REST API with Node.js, Express, and PostgreSQL

Apple pay in react native using stripe

What’s new in Vue 3? The most interesting new features [Examples]

React Class & Function Todo Lists

Social application with Vue.js and GO

being myself as a softeare egineer — in the age of the Aquarius

Google JavaScript Style Guide: Takeaways for TypeScript Developers

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Rohan Aggarwal

Rohan Aggarwal

Full stack developer

More from Medium

JavaScript Objects

Asynchronous JavaScript — Part 4…

Javascript, write it clean PART 1 : variables.

Debugging with Angular 9