what is immutability in js code example
Example 1: js immutability
const userProfile = {
username: 'Jack',
email: 'Jack@email',
socialMedia: {
twitter: '@jack',
facebook: 'jackm',
linkedIn: 'jackmay',
},
}
const newUserProfile = {
...userProfile,
email: 'JackNew@email',
socialMedia: { ...userProfile.socialMedia, twitter: '@newTwitter' },
}
console.log('orginal', userProfile)
console.log('new', newUserProfile)
Example 2: immutable values
let a = {
foo: 'bar'
};
let b = a;
a.foo = 'test';
console.log(b.foo);
console.log(a === b)
let a = 'test';
let b = a;
a = a.substring(2);
console.log(a)
console.log(b)
console.log(a === b)
let a = ['foo', 'bar'];
let b = a;
a.push('baz')
console.log(b);
console.log(a === b)
let a = 1;
let b = a;
a++;
console.log(a)
console.log(b)
console.log(a === b)