Golang Tutorials - Learn Go Programming with Easy Step-by-Step Guides

Explore comprehensive Golang tutorials for beginners and advanced programmers. Learn Go programming with easy-to-follow, step-by-step guides, examples, and practical tips to master Go language quickly.

Object Protection in JavaScript

Object Protection in JavaScript

Object Protection in JavaScript


What is Object Protection?

Object protection refers to techniques that restrict or control how an object’s properties can be modified, added, or deleted to preserve integrity and prevent unwanted changes.


Ways to Protect Objects in JavaScript

1. Object.freeze()

  • Makes an object immutable:

    • You cannot add, delete, or modify existing properties.

  • Shallow freeze only (nested objects are not frozen).

const person = {  name: "Alice",  age: 30};Object.freeze(person);person.age = 31;      // Ignored in strict mode, fails silently otherwiseperson.city = "NY";   // Cannot add new propertiesdelete person.name;   // Cannot delete propertiesconsole.log(person);  // { name: "Alice", age: 30 }

2. Object.seal()

  • Prevents adding or deleting properties.

  • Allows modification of existing properties.

const person = {  name: "Alice",  age: 30};Object.seal(person);person.age = 31;      // Allowedperson.city = "NY";   // Not alloweddelete person.name;   // Not allowedconsole.log(person);  // { name: "Alice", age: 31 }

3. Object.preventExtensions()

  • Prevents adding new properties only.

  • Existing properties can be modified or deleted.

const person = {  name: "Alice",  age: 30};Object.preventExtensions(person);person.city = "NY";   // Not allowedperson.age = 31;      // Alloweddelete person.name;   // Allowedconsole.log(person);  // { age: 31 }

Checking Protection Status

console.log(Object.isFrozen(person));        // true or falseconsole.log(Object.isSealed(person));        // true or falseconsole.log(Object.isExtensible(person));    // true or false

Summary

MethodCan Add PropertiesCan Delete PropertiesCan Modify Properties
Object.freeze()NoNoNo
Object.seal()NoNoYes
Object.preventExtensions()NoYesYes

Would you like to see examples with nested objects or Proxy-based protection?

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql