A partial archive of discourse.wicg.io as of Saturday February 24, 2024.

Compare by value with const variables


tl;dr: constant values are immutable and could be compared by value not identity…?


let a = new Set([ [1], [1] ]);

This produces a set with two members.


const rgb1 = [128,128,128];
const rgb2 = [128,128,128]; 
let rgb3 = [128,128,128];

let colors = new Set([ rgb1, rgb2]); 
let moreColors = new Set([...colors, rgb3])

// prints one color
// constants could be compared by value, not identity..?
for (let col of colors){

//  prints two lines, as one constant (read, immutable) and one let bound do not 
// compare as being equal
for (let col of moreColors) {

Does this make sense?


It’s an interesting idea, but it’s just not JavaScript compatible. (Say that I’m associating all objects that use the same array, and two separate const-defined arrays, which coincidentally have the same values in this revision of the script, are attached to different objects.)


I’m not quite following - could you show me in code what you mean?

const REDISGREEN_PORTS = [28015, 28016]
const REDISTOGO_PORTS = [28015, 28016]
var REDISCLOUD_PORTS = [28015, 28016]
var OPENREDIS_PORTS = [28015, 28016]

function removeAllConnectionsWithPortSpec(spec) {
  connections = connections.filter(conn => conn.spec == spec)

removeAllConnectionsWithPortSpec(REDISCLOUD_PORTS) //removes just the REDISCLOUD connections
removeAllConnectionsWithPortSpec(REDISTOGO_PORTS) //would remove the REDISTOGO connections *and* the REDISGREEN connections

const is not recursive. It prevents the reference from changing, but if the value being referred to is mutable, it can change freely. So you can’t do compare-by-value. (Or rather, it’s just as valid/invalid to do it on a const as it is for a let.)

What you want are Value Objects, which I think are showing up in ES2016. Here’s the latest proposal. They’re build on top of a frozen TypedArray, so you can be sure that they’re recursively immutable. As a bonus, you get a bunch of other goodies.


Thank you both for your replies, and understand what you mean. I had not grasped the non-recursive aspect of const - it feels a little strange, but, can use this now with more confidence. Appreciate the explanation.

The proposal here https://github.com/sebmarkbage/ecmascript-immutable-data-structures was linked on twitter. Needing new syntax now makes perfect sense.

Just as a final thought, I suppose another way of doing this could be something like

const immutable a = [1,2,3]; // or whatever
const b = [1,2,3];

a === b; // true

but, the syntax proposed in the link above is more succinct, and I suppose adding another keyword after const might have other pitfalls.

Regardless, both value types and the immutable data structure proposals are looking really interesting. Thumbs up for compare by value in JS coming soon :wink: