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 :: conditionally changing styled components based on props 
Javascript :: axios try catch 
Javascript :: is var is not blank then display value in javascript 
Javascript :: change theme in react-toastify 
Javascript :: pi in js 
Javascript :: emotion react 
Javascript :: 150 pound in kg 
Javascript :: javascript set to array 
Javascript :: settimeout vs requestanimationframe 
Javascript :: javascript get element by multiple class names 
Javascript :: redirect react router 
Javascript :: how to merge two sorted arrays in javascript 
Javascript :: jquery find div with data attribute value 
Javascript :: get name of class javascript 
Javascript :: jqiery check if scroll to end 
Javascript :: dynamic import javascript 
Javascript :: delete local storage javascript 
Javascript :: Reverse numbers from an array in javascript 
Javascript :: google maps autocomplete js events 
Javascript :: ERESOLVE unable to resolve dependency tree 
Javascript :: clear all intervals js 
Javascript :: electron no resize 
Javascript :: split decimal value in javascript 
Javascript :: jquery onload function for div 
Javascript :: Javascript form check to see if return or enter was pressed 
Javascript :: js math.trunc 
Javascript :: stop interval js 
Javascript :: js largest number in array 
Javascript :: how to loop an object in javascript 
Javascript :: typeof 
ADD CONTENT
Topic
Content
Source link
Name
6+4 =