Answers for "A mutable object"

2

A mutable object

Mutable is a type of variable that can be changed. 
In JavaScript, only Objects and Arrays(technically a type of object) are 
mutable, not primitive(immutable) values.

Immutables are the objects whose state cannot be changed once the object is 
created. Boolean, Null, Undefined, Number, String, and Symbols are immutable.
Posted by: Guest on January-02-2021
0

immutable values

let a = {
    foo: 'bar'
};

let b = a;

a.foo = 'test';

console.log(b.foo); // test
console.log(a === b) // true
let a = 'test';
let b = a;
a = a.substring(2);

console.log(a) //st
console.log(b) //test
console.log(a === b) //false
let a = ['foo', 'bar'];
let b = a;

a.push('baz')

console.log(b); // ['foo', 'bar', 'baz']

console.log(a === b) // true
let a = 1;
let b = a;
a++;

console.log(a) //2
console.log(b) //1
console.log(a === b) //false
Posted by: Guest on July-31-2020
0

what is immutable

// by negative example here is how to make a javascript immutable

'use strict';

const a = Object.freeze([4, 5, 6]);

// Instead of: a.push(7, 8, 9);
const b = a.concat(7, 8, 9);

// Instead of: a.pop();
const c = a.slice(0, -1);

// Instead of: a.unshift(1, 2, 3);
const d = [1, 2, 3].concat(a);

// Instead of: a.shift();
const e = a.slice(1);

// Instead of: a.sort(myCompareFunction);
const f = R.sort(myCompareFunction, a); // R = Ramda

// Instead of: a.reverse();
const g = R.reverse(a); // R = Ramda
Posted by: Guest on November-19-2020

Browse Popular Code Answers by Language