Curriculum
Course: JavaScript Basic
Login

Curriculum

JavaScript Basic

JSHome

0/216
Text lesson

JavaScript Object.seal()

The Object.seal() method prevents the addition or deletion of properties.

It also makes existing properties non-configurable.

You can use the Object.isSealed() method to check if an object is sealed.

Note:

The Object.seal() method will fail silently in non-strict mode but will throw a TypeError in strict mode.

Example

“use strict”
// Create Object
const person = {
  firstName: “John”,
  lastName: “Doe”,
  age: 50,
  eyeColor: “blue”
};

// Seal Object
Object.seal(person)

// This will throw an error
delete person.age;

Since arrays are objects, they can also be sealed.

Example

// Create Array
const fruits = [“Banana”“Orange”“Apple”“Mango”];
Object.seal(fruits);

// This will throw an error:
fruits.push(“Kiwi”);

JavaScript Object.isSealed()

The Object.isSealed() method checks if an object is sealed.

It returns true if the object is sealed.

Examples

// Create Object
const person = {firstName:“John”, lastName:“Doe”};

// Seal Object
Object.seal(person);

// This will return true
let answer = Object.isSealed(person);
// Create Array
const fruits = [“Banana”“Orange”“Apple”“Mango”];

// Seal Array
Object.seal(fruits);

// This will return true
let answer = Object.isSealed(fruits);

JavaScript Object.freeze()

The Object.freeze() method prevents any changes to an object.

Frozen objects become read-only, disallowing modifications, additions, or deletions of properties.

Note:

The Object.freeze() method will fail silently in non-strict mode but will throw a TypeError in strict mode.

Example

“use strict”
// Create Object
const person = {
  firstName: “John”,
  lastName: “Doe”,
  age: 50,
  eyeColor: “blue”
};

// Freeze Object
Object.freeze(person)

// This will throw an error
person.age = 51;

Since arrays are objects, they can also be frozen.

Example

const fruits = [“Banana”“Orange”“Apple”“Mango”];
Object.freeze(fruits);

// This will trow an error:
fruits.push(“Kiwi”);

JavaScript Object.isFrozen()

The Object.isFrozen() method checks if an object is frozen.

It returns true if the object is frozen.

Examples

// Create Object
const person = {firstName:“John”, lastName:“Doe”};

// Freeze Object
Object.freeze(person);

// This will return true
let answer = Object.isFrozen(person);
// Create Array
const fruits = [“Banana”“Orange”“Apple”“Mango”];
Object.freeze(fruits);

// This will return true:
let answer = Object.isFrozen(fruits);