Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

how to create immutable object in javascript

The Object.freeze() method freezes an object: 
that is, prevents new properties from being added to it; 
prevents existing properties from being removed; 
and prevents existing properties, or their enumerability, 
configurability, or writability, from being changed, 
it also prevents the prototype from being changed. 
The method returns the object in a frozen state.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze

const obj = {
  prop: 42
};

Object.freeze(obj);

obj.prop = 33;
// Throws an error in strict mode

console.log(obj.prop);
// expected output: 42
Comment

create immutable object in javascript

let x = {name: "blood", color: "red"}
let {...y} = x

// let's update the value of "x"
x.name = "strawberry"

console.log(x) // will return {name: "strawberry", color: "red"}
console.log(y) // will return {name: "blood", color: "red"}
/* "y" haven't changed because it copied the value of "x" and made himself
a whole separated ohject, instead of just coping the reference of "x"
(reference copy case:- let y = x) */
/* NOTE: get some youtube classes about javascript reference type and primitive
data types, if you're not clear enough about what i mean by "reference" */
Comment

PREVIOUS NEXT
Code Example
Javascript :: reverse array recursion javascript 
Javascript :: types of method in js 
Javascript :: use length to resize an array 
Javascript :: app.js not found in laravel 8 
Javascript :: uppercase each word javascript 
Javascript :: validate firstname in javascript 
Javascript :: window viewport width 
Javascript :: set twig variable from javascript 
Javascript :: javascript class in external file 
Javascript :: Looping arrays with for loop 
Javascript :: Is Even 
Javascript :: how to defined an array in js 
Javascript :: declaring variable react hooks 
Javascript :: playSound in draw loop javascript 
Javascript :: sum in javascript 
Python :: import keys selenium 
Python :: get python version jupyter 
Python :: suppress pandas future warnings 
Python :: converting string to datetime pandas 
Python :: dataframe to csv without ids 
Python :: torch device 
Python :: selenium python maximize window 
Python :: items of a list not in another list python 
Python :: truncate templat tag django 
Python :: How to play music without pygame 
Python :: change tkinter window name 
Python :: python alphabet capital 
Python :: delete rows based on condition python 
Python :: code how pandas save csv file 
Python :: python check file extension 
ADD CONTENT
Topic
Content
Source link
Name
1+7 =