Encodera

Thanks for reading!

Donate to the site — we work hard for you.

JavaScript reference

Object.freeze

Prevents any changes to an object.

Available since: ES5

Syntax

Object.freeze(obj)

Parameters

ParameterTypeDescription
objobjectThe object to freeze.

Return value

objectThe same object, now frozen.

Examples

Changes are silently ignored:

const config = Object.freeze({ port: 3000 });
 
config.port = 8080;
config.host = 'localhost';
 
console.log(config);

Output:

{
  "port": 3000
}

In strict mode (in modules and classes) a change throws an error:

'use strict';
const config = Object.freeze({ port: 3000 });
 
try {
  config.port = 8080;
} catch (error) {
  console.log(error.name);
}

Output:

TypeError

Notes

Freezing is shallow: nested objects can still change unless you freeze them too.

const and Object.freeze() are different: const forbids assigning another object to the variable, freeze forbids changing the object itself.

See also

  • Object.isFrozen — Checks whether an object is frozen.
  • Object.seal — Forbids adding and removing properties but lets existing ones change.
  • const — Declares a variable that cannot be reassigned.

Related recipes

In the tutorial

  • Immutability — Mutable and immutable data in JavaScript: object references, copying with spread, the toSorted and with methods, Object.freeze and structuredClone.

Thanks for reading!

Donate to the site — we work hard for you.