Using getters and setters for objects

Interesting. I find const in JavaScript less than worthless, although 99% of that is probably the fault of my brain that has been trained on decades of C/C++.

In that world, we have const char *p, which means “you can’t modify the string that p is pointing to”. That is the concept of object immutability that you seek (and I agree, it’s a great help). We also have char * const p which means “you can’t reassign p to point at some other string, but you can use p to modify the string it’s pointing at”. That’s IMHO considerably less useful, and by that I mean I still haven’t come across a single situation where I was glad to have that feature.

Sadly, that second meaning is all we get out of JavaScript’s const. So:

const car = {model: "Lotus", color: "red"};
// won't let us do this
car = {model: "Cadillac", color: "white"};

// but no problem here
this.testDrive(car);

testDrive(c) {
  car.model = 'Pinto'; // ha ha suckers
}

So since JavaScript’s const lulls me into a false sense of security, but doesn’t actually protect against what I want to protect against, I just pretend it doesn’t exist.

1 Like